Insert a column name into each data frame value in R

Hoping this is not a repetition - I had a search, but I can not find what I am looking for.

I have dataframe (df) in R

  1 2 3 4 5 
1 1 0.5 0.5 0 1
2 0.5 0.5 0.5 0 1
3 1 1 0 0 1
4 1 1 0 0 1 
5 1 1 0 0 1

(with 1-5 specifying row and column names)

I would like to insert a column name in each cell separated by ":" so that it looks like this:

  1 2 3 4 5 
1 1:1 2:0.5 3:0.5 4:0 5:1 
2 1:0.5 2:0.5 3:0.5 4:0 5:1 
3 1:1 2:1 3:0 4:0 5:1 
4 1:1 2:1 3:0 4:0 5:1 
5 1:1 2:1 3:0 4:0 5:1 

However, my actual data is slightly larger.

I currently have

apply(df, 2, function(x) paste(colnames(df)[x], x, sep=":"))

Of course, this does not work, since colnames (df) [x] makes no sense. Is there anything I can add to this first term “paste” to get this sort? Or another function to do a better job?

Thank.

+4
source share
3 answers

col(., as.factor = TRUE) , ( ).

df[] <- paste(col(df, TRUE), as.matrix(df), sep = ":")

:

      1     2     3   4   5
1   1:1 2:0.5 3:0.5 4:0 5:1
2 1:0.5 2:0.5 3:0.5 4:0 5:1
3   1:1   2:1   3:0 4:0 5:1
4   1:1   2:1   3:0 4:0 5:1
5   1:1   2:1   3:0 4:0 5:1

, as.factor = TRUE . , .

df[] <- paste(col(df), as.matrix(df), sep = ":")

P.S. 100% .

:

df <- structure(list(`1` = c(1, 0.5, 1, 1, 1), `2` = c(0.5, 0.5, 1, 
1, 1), `3` = c(0.5, 0.5, 0, 0, 0), `4` = c(0L, 0L, 0L, 0L, 0L
), `5` = c(1L, 1L, 1L, 1L, 1L)), .Names = c("1", "2", "3", "4", 
"5"), class = "data.frame", row.names = c("1", "2", "3", "4", 
"5"))
+4

, Map lapply,

df[] <- Map(paste, names(df), df, sep = ':')

names(df), .. 1, paste df, . df[] data.frame , , .

:

df
##       1     2     3   4   5
## 1   1:1 2:0.5 3:0.5 4:0 5:1
## 2 1:0.5 2:0.5 3:0.5 4:0 5:1
## 3   1:1   2:1   3:0 4:0 5:1
## 4   1:1   2:1   3:0 4:0 5:1
## 5   1:1   2:1   3:0 4:0 5:1
+2

We can unlistset data pastewith replicated column name elements

df[] <- paste(names(df)[col(df)], unlist(df), sep=":")
df
#      1     2     3   4   5
#1   1:1 2:0.5 3:0.5 4:0 5:1
#2 1:0.5 2:0.5 3:0.5 4:0 5:1
#3   1:1   2:1   3:0 4:0 5:1
#4   1:1   2:1   3:0 4:0 5:1
#5   1:1   2:1   3:0 4:0 5:1

data

df <- structure(list(`1` = c(1, 0.5, 1, 1, 1), `2` = c(0.5, 0.5, 1, 
1, 1), `3` = c(0.5, 0.5, 0, 0, 0), `4` = c(0L, 0L, 0L, 0L, 0L
), `5` = c(1L, 1L, 1L, 1L, 1L)), .Names = c("1", "2", "3", "4", 
 "5"), class = "data.frame", row.names = c("1", "2", "3", "4", 
 "5"))
0
source

Source: https://habr.com/ru/post/1666952/


All Articles