我遵循data frame
,我想将第一列的值保留为子列表名称,将第二列的值保留为其元素。
输入-
var <- c("a","b","c","d")
val <- c("0-1-2-NA","0-1","0-2-4","0-NA")
dt <- data.frame(var,val, stringsAsFactors = FALSE)
> dt
var val
1 a 0-1-2-NA
2 b 0-1
3 c 0-2-4
4 d 0-NA
所需的输出-
$a
[1] 0 1 2 NA
$b
[1] 0 1
$c
[1] 0 2 4
$d
[1] 0 NA
注意-我还想在创建列表之前用split
来-
个值。
答案 0 :(得分:2)
具有strsplit
的基本R解决方案。
dat <- strsplit(dt$val, split = "-")
names(dat) <- dt$var
dat
# $a
# [1] "0" "1" "2" "NA"
#
# $b
# [1] "0" "1"
#
# $c
# [1] "0" "2" "4"
#
# $d
# [1] "0" "NA"
要自动转换字符串,请添加type.convert
(或as.integer
或as.numeric
):
res <- with(dt, lapply(strsplit(setNames(val, var), "-"), type.convert))
str(res)
# List of 4
# $ a: int [1:4] 0 1 2 NA
# $ b: int [1:2] 0 1
# $ c: int [1:3] 0 2 4
# $ d: int [1:2] 0 NA