将列名称与数据框中的因子级别结合起来

时间:2018-12-03 10:10:14

标签: r

我有这个:

df1 <- data.frame(A = c('a', 'b', 'c'), B = c('d', 'e', 'c'))

,并希望将其转换为此:

    A   B
1 A:a B:d
2 A:b B:e
3 A:c B:c

我当前无法正常工作的惨痛“循环”尝试(首选使用应用版本)是这样的:

for (row in 1:nrow(df1)) {
    for (col in 1:ncol(df1)) {
        levels(colnames(df1)[col])[levels(colnames(df1)[col]) == df1[row, col]] <- paste0(colnames(df1)[col], ":", df1[row, col])
    }
}

3 个答案:

答案 0 :(得分:4)

使用mapply的一种方式:

data.frame(mapply(function(x, y) paste0(y, ':', x), df1, c('A', 'B')))
#    A   B
#1 A:a B:d
#2 A:b B:e
#3 A:c B:c

或者您可以这样做:

data.frame(A = paste0('A:', df1$A),
           B = paste0('B:', df1$B))

但是如果您有多个要使用此逻辑的列,我会选择第一个选项。

答案 1 :(得分:3)

使用from("routeId").removeHeaders("CamelServiceCall*").end(); 的选项,其中我们遍历每一列,并使用lapply列名以及列值。

paste

答案 2 :(得分:1)

如果要使用tidyverse进行操作:

df1 %>%
 rowid_to_column() %>% #Creating row IDs
 gather(var, val, -rowid) %>% #Transforming the data from wide to long
 mutate(temp = paste(var, val, sep = ":")) %>% #Combining the column names with the level of factors
 select(-val) %>%
 spread(var, temp) %>% #Transforming the data back to wide format
 select(-rowid) #Deleting the redundant variable

    A   B
1 A:a B:d
2 A:b B:e
3 A:c B:c
相关问题