本文介绍了按组拆分列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数据看起来有点像这样:

I have some data that looks a little bit like this:

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 = "")

我希望看起来更像这样...

I'd like it to look more like this ...

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页面答案。我正在寻找什么命令?

It seems like there should be a straightforward way to break out the "amounts" column, but I'm not coming up with it. Happy to take a "RTFM page for this particular command" answer. What's the command I'm looking for?

推荐答案

(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

这篇关于按组拆分列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 16:20