gpt4 book ai didi

r - 将 csv 值转换为 R 中的表

转载 作者:行者123 更新时间:2023-12-04 06:29:46 25 4
gpt4 key购买 nike

我有一些来自民意调查的数据,如下所示:

                                    Freetime_activities
1 Travelling, On the PC, Clubbing
2 Sports, On the PC, Clubbing
3 Clubbing
4 On the PC
5 Travelling, On the PC, Clubbing
6 On the PC
7 Watching TV, Travelling

我想获取每个值的计数(旅行/在电脑上/等等),但我在分割这些值时遇到了麻烦。 R 中是否有一个函数可以执行以下操作:

split("A,B,C") -> 
1 A
2 B
3 C

或者是否有直接的解决方案来直接从列中计算值?

最佳答案

我们可以使用strsplit按分隔符 ", " 分割列), unlist list输出然后使用table获取频率

 tbl <- table(unlist(strsplit(as.character(df1$Freetime_activities),
", ")))
as.data.frame(tbl)
# Var1 Freq
#1 Clubbing 4
#2 On the PC 5
#3 Sports 1
#4 Travelling 3
#5 Watching TV 1


注意:这里使用as.character如果该列是 factorstrsplit只能取character向量。

或者另一种选择是使用 scan提取元素,然后使用 table获取频率。

 table(trimws(scan(text = as.character(df1$Freetime_activities),
what = "", sep = ",")))

或者使用read.tableunlisttable

table(unlist(read.table(text = as.character(df1$Freetime_activities), 
sep = ",", fill = TRUE, strip.white = TRUE)))

编辑:基于@David Arenburg 的评论。

数据

df1 <- structure(list(Freetime_activities = c("Travelling, On the PC, 
Clubbing",
"Sports, On the PC, Clubbing", "Clubbing", "On the PC", "Travelling,
On the PC, Clubbing",
"On the PC", "Watching TV, Travelling")),
.Names = "Freetime_activities",
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7"))

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

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