【问题标题】:Converting csv values to table in R将csv值转换为R中的表
【发布时间】:2016-04-22 14:10:45
【问题描述】:

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

                                    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

我想获取每个值的计数(旅行多少次/在 PC 上等),但我无法拆分这些值。 R中是否有一个函数可以做例如:

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

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

【问题讨论】:

    标签: r parsing csv split


    【解决方案1】:

    我们可以使用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,以防列是factor,因为strsplit 只能采用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 的 cmets。

    数据

    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"))
    

    【讨论】:

    • 这有一些不良影响 -> Var1 Freq 1 \n"在 PC 上 1 2 \n"看电视 1 3 "俱乐部" 1 4 "在 PC 上 5 5 "在 PC 上" 8
    • @MarioStoilov 我不确定我是否理解不良影响。根据您展示的示例,我得到了您描述的频率。
    • 我是说我得到了各种变量,应该是一样的,比如 (\n"On the PC, "On the PC, "On the PC")
    • 似乎 as.character 表现不佳 -> as.character(myData[4]) [1] "c(\"Traveling,On PC,Clubbing\", \"Sports,On电脑,夜总会\",....
    • 我应该指出我正在从 Excel 表中读取数据
    猜你喜欢
    • 2021-07-21
    • 2017-10-30
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 2016-07-02
    • 2018-09-03
    相关资源
    最近更新 更多