小编Sha*_*yna的帖子

将一列列表强制转换为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)
Run Code Online (Sandbox Code Playgroud)

对于出现多次的每个id,连接relationship_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
Run Code Online (Sandbox Code Playgroud)

我想出了导致这个错误的原因:

class(combo$relationship_id)
[1] "list"
Run Code Online (Sandbox Code Playgroud)

但是当我尝试将列表向量强制转换为字符向量时:

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")
Run Code Online (Sandbox Code Playgroud)

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

r

5
推荐指数
1
解决办法
67
查看次数

标签 统计

r ×1