问题:
我有一个字符串向量foo:
>foo = c("1x2","3x4","5x6","7x8","9x10")
我将单个字符串拆分为“x”并将结果粘贴到goo:
>goo = strsplit(foo, "x")
>goo
[[1]]
[1] "1" "2"
[[2]]
[1] "3" "4"
[[3]]
[1] "5" "6"
[[4]]
[1] "7" "8"
[[5]]
[1] "9" "10"
如何从此列表中提取第一个和第二个“列”? (我想要(1,3,5,7,9)和(2,4,6,8,10))
答案 0 :(得分:5)
使用sapply
使用“[[”:
sapply(goo, "[[" , 1)
[1] "1" "3" "5" "7" "9"
我一直认为这应该是结果,但我可能不理解这些问题。
答案 1 :(得分:1)
> result <- do.call(rbind, goo)
> result
[,1] [,2]
[1,] "1" "2"
[2,] "3" "4"
[3,] "5" "6"
[4,] "7" "8"
[5,] "9" "10"
> result[, 1] # column 1
[1] "1" "3" "5" "7" "9"
> result[, 2] # column 2
[1] "2" "4" "6" "8" "10"
答案 2 :(得分:0)
最简单的方法是将结果包装在sapply
语句
odd_results <- sapply(goo, function(x) x[1])
和
even_results <- sapply(goo, function(x) x[2])
答案 3 :(得分:0)
您需要按位置指定列表元素的提取。
# load data
foo <- c("1x2","3x4","5x6","7x8","9x10")
# split foo by 'x'
foo.list <- strsplit( x = foo, split = "x", fixed = TRUE )
# store the first and second elements of each list in a data frame
foo.df <-
data.frame(
First_Element = unlist( lapply( X = foo.list, FUN = "[[", FUN.VALUE = 1 ) )
, Second_Element = unlist( lapply( X = foo.list, FUN = "[[", FUN.VALUE = 2 ) )
)
答案 4 :(得分:0)
为了多样化,您可以使用
goo <- unlist(strsplit(foo, "x"))
a <- goo[seq(1, length(goo), 2)]
b <- goo[seq(2, length(goo), 2)]
哪个收益
[1] "1" "3" "5" "7" "9"
和
[1] "2" "4" "6" "8" "10"
分别