gpt4 book ai didi

r - R中数据框中连续的字符串,列表对

转载 作者:行者123 更新时间:2023-12-04 12:08:26 28 4
gpt4 key购买 nike

我有一个数据框如下:

date = "2000"
values = c("a","b","d")
df <- data.frame(date=date,values= values)
df
date values
1 2000 a
2 2000 b
3 2000 d

实际上我在 values 中有数千个值 field 。因此,我不想作为单独的行打印,而是让数据框包含一行,其中包含所有信息。即,类似于:

1 2000    a,b,d

这在 R 中是否可行,类似于 map<String,arrayList(String)>在 Java 中?

最佳答案

不清楚您想要什么,但这里有一些带有 aggregate 的代码可以帮助您入门:

> df$values <- as.character(df$values)
> # A `list` of the values
> (da1 <- aggregate(values ~ date, df, I, simplify=FALSE))
date values
1 2000 a, b, d
> str(da1)
'data.frame': 1 obs. of 2 variables:
$ date : Factor w/ 1 level "2000": 1
$ values:List of 1
..$ 0:Class 'AsIs' chr [1:3] "a" "b" "d"

> # All the values collapsed into one string
> (da2 <- aggregate(values ~ date, df, paste, collapse = ", ", simplify=FALSE))
date values
1 2000 a, b, d
> str(da2)
'data.frame': 1 obs. of 2 variables:
$ date : Factor w/ 1 level "2000": 1
$ values:List of 1
..$ 0: chr "a, b, d"

我已经展示了 str 结构,因此您可以在这里看到两个示例之间的区别。


如果我正确理解您在下面的评论,您可能也对此感兴趣:

> date = "2000"
> values = c("a", "b", "d")
> (temp <- data.frame(date, values = I(list(values))))
date values
1 2000 a, b, d
> str(temp)
'data.frame': 1 obs. of 2 variables:
$ date : Factor w/ 1 level "2000": 1
$ values:List of 1
..$ : chr "a" "b" "d"
..- attr(*, "class")= chr "AsIs"

换句话说,如果您想在创建data.frame 时将list 作为列项,则必须使用I功能。

关于r - R中数据框中连续的字符串,列表对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16211109/

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