简体   繁体   中英

Is there a way to change data frame entries in R from numeric to a specific character?

If I have a data frame like so:

df <- data.frame(
a = c(1,1,1,2,2,2,3,3,3),
b = c(1,2,3,1,2,3,1,2,3)
)

which looks like this:

> df
  a b
  1 1
  1 2
  1 3
  2 1
  2 2
  2 3
  3 1
  3 2
  3 3

Is there a quick way to change the columns a and b to match the example below, without explicitly having to type it all out?

> df
   a  b
  a1 b1
  a1 b2
  a1 b3
  a2 b1
  a2 b2
  a2 b3
  a3 b1
  a3 b2
  a3 b3

In other words, Im trying to take the name of the column and just place it in front of the value that was in that row originally.

We can use cur_column to return the corresponding column name within across and paste ( str_c ) the column value with the corresponding column name

library(dplyr)
library(stringr)
df1 <- df %>% 
      mutate(across(everything(), ~ str_c(cur_column(), .)))

-output

df1
#   a  b
#1 a1 b1
#2 a1 b2
#3 a1 b3
#4 a2 b1
#5 a2 b2
#6 a2 b3
#7 a3 b1
#8 a3 b2
#9 a3 b3

Or using base R

df[] <- Map(paste0, names(df), df)

Or another option is

df[] <-  paste0(names(df)[col(df)], unlist(df))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM