r - 将一列列表强制转换为 R 数据框中的字符串

标签 r

创建示例数据:

id <- c(12, 32, 42, 42, 52, 52, 67, 67)
relationship_id <- c(15,1,59,1,61,6,59,1)
sample.data <- data.frame(id,relationship_id)

对于每个出现多次的 id,连接relation_id:
combo <- aggregate(relationship_id ~ id, data = sample.data, paste, sep=",")
table(combo$relationship_id)
Error in table(combo$relationship_id) :
  all arguments must have the same length

我想出了是什么导致了这个错误:
class(combo$relationship_id)
[1] "list"

但是当我尝试将列表向量强制转换为字符向量时:
combo["relationship_id"] <- lapply(combo["relationship_id"], as.character)
> head(combo)    
  id relationship_id
1 12              15
2 32               1
3 42    c("59", "1")
4 52    c("61", "6")
5 67    c("59", "1")

它包括连接语法......我知道我可以解析输出以使其可用,但为什么会发生这种情况?有没有更简单的方法来清理输出?

最佳答案

你正试图解决错误的问题。如果您真的想将这些值折叠为单个字符向量,则应该使用 collapse = ","而不是 sep .

combo <- aggregate(relationship_id ~ id, data = sample.data, 
                   paste, collapse=",")
table(combo$relationship_id)
# 
#    1   15 59,1 61,6 
#    1    1    2    1 

关于r - 将一列列表强制转换为 R 数据框中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27802401/

相关文章:

R:隐藏 lm 显示中的控制变量

r - 为什么ggplot中的箱线图需要x轴和y轴?

r - 使用 data.table 快速读取并组合多个文件(使用 fread)

r - vcovHC 和置信区间

r - 应该是具有相同水平,误差和引用的因素

r - 在 ggplot2 (facet_grid) 中的特定方面之间添加空间

r - 如何使用 R 格子 xyplot 根据数值阈值对点进行着色

r - SuperLearner预测错误

R:删除少于特定阈值非零值的行

R - 填充 df 中的列