gpt4 book ai didi

r - 将数据框转换为R中的列表

转载 作者:行者123 更新时间:2023-12-04 10:48:31 25 4
gpt4 key购买 nike

我想将数据框转换为列表。见表 1 中的输入。请参见表 2 中的输出。当您从环境中打开 R 中的列表时。名称 - 以下名称 clus1、clus2...类型 - 应包含 V1 列中的值值 - 长度为 3 的列表

Table 1
V1 V2 V3
clus1 10 a d
clus2 20 b e
clus3 5 c f

Table 2
$`clus1`
[1] "a" "d"

$`clus2`
[2] "b" "e"

$`clus3`
[2] "c" "f"

最佳答案

t1 = read.table(text = "      V1 V2 V3
clus1 10 a d
clus2 20 b e
clus3 5 c ''", header = T)

result = split(t1[, 2:3], f = row.names(t1))
result = lapply(result, function(x) {
x = as.character(unname(unlist(x)))
x[x != '']})
result
# $clus1
# [1] "a" "d"
#
# $clus2
# [1] "b" "e"
#
# $clus3
# [1] "c"

在这种特殊情况下,如果我们先转换为矩阵,我们可以更直接一点:

r2 = split(as.matrix(t1[, 2:3]), f = row.names(t1))
r2 = lapply(r2, function(x) x[x != ''])
# same result

关于r - 将数据框转换为R中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58609549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com