0

我有一个文本文件,其格式如下:

groupA, 123
groupA, 32
groupB, 222
groupA, 212
groupB, 213
...

我怎样才能轻松地形成两个向量[123, 32, 212, ...][222, 213, ...]分别用于 groupA 和 groupB?

谢谢你。

4

2 回答 2

1

您可以简单地使用split. 这将产生一个命名列表,其中每个列表项都是您的向量之一。

mydf <- read.csv(header = FALSE, text = "groupA, 123
groupA, 32
groupB, 222
groupA, 212
groupB, 213")
mydf2 <- split(mydf$V2, mydf$V1)
mydf2
# $groupA
# [1] 123  32 212
# 
# $groupB
# [1] 222 213

如果您不想要一个list(尽管我发现在我的工作区中有很多单个矢量对象更可取),您可以使用lapplyand assign

## Verify that there are no objects currently named `groupA` or `groupB`
ls(pattern = "group")
# character(0)

## Assign each list item to a new object, making use of the `names` of the list
invisible(lapply(names(mydf2), 
                 function(x) assign(x, mydf2[[x]], envir=.GlobalEnv)))

## Verify the presence and values of the new vectors
ls(pattern = "group")
# [1] "groupA" "groupB"
groupA
# [1] 123  32 212
groupB
# [1] 222 213
于 2013-03-23T05:50:57.800 回答
0

Ananda Mahto 的答案更通用(也很有趣!),但这里有一个简单的子设置方法,它也可以获取两个向量:

mydf <- read.csv(header = FALSE, text = "groupA, 123
groupA, 32
groupB, 222
groupA, 212
groupB, 213")

# the dataframe is automatically assigned
# column names V1 and V2...

# vector of V2 for groupA
mydf[mydf$V1 == "groupA",]$V2
[1] 123  32 212

# vector of V2 for groupB
mydf[mydf$V1 == "groupB",]$V2
[1] 222 213
于 2013-03-23T16:38:57.610 回答