【问题标题】:How do I convert all dataframe rows to a unique string in R [duplicate]如何将所有数据框行转换为 R 中的唯一字符串 [重复]
【发布时间】:2020-11-08 22:07:36
【问题描述】:

我有一个数据框:

V1,V2,V3,V4,V5
1.12331,4.331123,4.12335435,1,"asd"
1.123453345,5.654456,4.889999,1.45456,"qwe"
2.00098,5.5445,4.768799,1.999999,"ttre"

我想将第一列或所有列(如果可能的话)提取到一个字符串变量中。

我正在尝试下面的代码:

library(tidyverse)
td <- read_csv("test.csv")

将所有DataFrame转换为字符串

var_text <- toString(td)

但结果仍然不是我所期望的。

[1] "c(1.12331, 1.123453345, 2.00098), c(4.331123, 5.654456, 5.5445), c(4.12335435, 4.889999, 4.768799), c(1, 1.45456, 1.999999)”

我需要类似的东西:

strResult = "1.12331, 1.123453345, 2.00098, 4.331123, 5.654456, 5.5445, 4.12335435, 4.889999, 4.768799, 1, 1.45456, 1.999999"

【问题讨论】:

    标签: r string dataframe


    【解决方案1】:

    unlistdata.frame 之后尝试paste

    paste(unlist(df[-5]), collapse = ", ")
    #[1] "1.12331, 1.123453345, 2.00098, 4.331123, 5.654456, 5.5445, 4.12335435, 4.889999, 4.768799, 1, 1.45456, 1.999999"
    

    【讨论】:

      【解决方案2】:

      试试这个:

      #Data
      df <- structure(list(V1 = c(1.12331, 1.123453345, 2.00098), V2 = c(4.331123, 
      5.654456, 5.5445), V3 = c(4.12335435, 4.889999, 4.768799), V4 = c(1, 
      1.45456, 1.999999), V5 = c("asd", "qwe", "ttre")), row.names = c(NA, 
      -3L), class = "data.frame")
      
      #Code
      #Create chain
      df$chain <- apply(df,1,function(x) paste(x,collapse = ','))
      #Now collapse all chain
      paste(df$chain,collapse = ',')
      
      [1] "1.123310,4.331123,4.123354,1.000000,asd,1.123453,5.654456,4.889999,1.454560,qwe,2.000980,5.544500,4.768799,1.999999,ttre"
      

      【讨论】:

        【解决方案3】:

        unlist 然后转成字符串:

        toString(unlist(df[-5]))
        #[1] "1.12331, 1.123453345, 2.00098, 4.331123, 5.654456, 5.5445, 4.12335435, 4.889999, 4.768799, 1, 1.45456, 1.999999"
        

        或者将其转换为矩阵。

        toString(as.matrix(df[-5]))
        

        在这里,我排除了最后一列,因为它不包含在预期的输出中。

        【讨论】:

        • toString(unlist(td[1:4])) 和 toString(as.matrix(td[1:4])) 两者都有效!非常感谢!
        • @BrunoSoares 很高兴能帮上忙!如果您觉得它对您有用,请随时点击左侧投票按钮旁边的复选标记accept the answer。 :-) 每个帖子只能接受一个答案。
        猜你喜欢
        • 2022-11-04
        • 2022-08-12
        • 1970-01-01
        • 1970-01-01
        • 2017-06-24
        • 2017-07-16
        • 2018-01-02
        • 2020-01-24
        • 1970-01-01
        相关资源
        最近更新 更多