This question already has answers here:
Split comma-separated strings in a column into separate rows

(6个答案)


4年前关闭。




我有一些看起来像这样的数据:
test.frame <- read.table(text = "name   amounts
                                JEAN  318.5,45
                             GREGORY 1518.5,67,8
                              WALTER  518.5
                               LARRY  518.5,55,1
                               HARRY  318.5,32
                         ",header = TRUE,sep = "")

我希望它看起来更像这样...
name   amount
JEAN  318.5
JEAN 45
GREGORY 1518.5
GREGORY 67
GREGORY 8
WALTER  518.5
LARRY  518.5
LARRY  55
LARRY  1
HARRY  318.5
HARRY  32

似乎应该有一种直接的方法来分解“金额”列,但我没有提出。很高兴获得“此特定命令的RTFM页面”答案。我要寻找的命令是什么?

最佳答案

(test.frame <- read.table(text = "name   amounts
                                JEAN  318.5,45
                             GREGORY 1518.5,67,8
                              WALTER  518.5
                               LARRY  518.5,55,1
                               HARRY  318.5,32
                         ",header = TRUE,sep = ""))


#      name     amounts
# 1    JEAN    318.5,45
# 2 GREGORY 1518.5,67,8
# 3  WALTER       518.5
# 4   LARRY  518.5,55,1
# 5   HARRY    318.5,32

tmp <- setNames(strsplit(as.character(test.frame$amounts),
                split = ','), test.frame$name)

data.frame(name = rep(names(tmp), sapply(tmp, length)),
           amounts = unlist(tmp), row.names = NULL)

#       name amounts
# 1     JEAN   318.5
# 2     JEAN      45
# 3  GREGORY  1518.5
# 4  GREGORY      67
# 5  GREGORY       8
# 6   WALTER   518.5
# 7    LARRY   518.5
# 8    LARRY      55
# 9    LARRY       1
# 10   HARRY   318.5
# 11   HARRY      32

关于r - 按组拆分列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24249351/

10-12 23:14