【问题标题】:read line by line a csv file in R and create a feature?在R中逐行读取一个csv文件并创建一个特征?
【发布时间】:2020-05-17 06:21:52
【问题描述】:

我已将插值数据存储到一个包含 181 行的 csv 文件中,其中每一行的第一个元素由标签表示,其余的是时间序列数据,例如这种格式:

第一行:0、980、888、720,987,543

第二行:0, 880, 999, 820,990,888, 980, 898, 780,987

第三行:1、945、856、767,745,883

第 4 行:2、780、899、920,890,988、780、998、870,787

第 5 行:2、800、900、822,999,880、988、899

其余 181 行以此类推,其中标签为 0、1、2、3、4、5、6。另外,请注意我的每一行都有不同的长度。 我想创建特征,(通过应用让我们说,mean()是特征之一)只使用时间序列,即“980、888、720,987,543”,不包括“标签y”,即0,我想要为每一行执行此操作并创建一个包含 33 个特征和标签的数据框,例如:

dim(labl_feat_df)[1] # 181 rows
dim(labl_feat_df)[2] # 34 columns (33 features and the label)

所以 labl_feat_df 看起来像:

     label  mean(TS)  SD(TS) ........ feat33
1     0
2     0
.
.
.
181   6

其中 mean(TS) 和 sd(TS) 是第一个和第二个特征。

所以我的问题是:如何读取不同长度的文件?如果应该逐行进行,那么创建这 33 个特征并将它们添加到数据框中的可能性和效率如何?

【问题讨论】:

    标签: r machine-learning time-series dataset


    【解决方案1】:

    1) dplyr/tidyr 在最后的 Note 中使用 Lines,读入,添加行号,id,然后从宽到长重塑。删除 NA 行并汇总。

    library(dplyr)
    library(tidyr)
    
    DF <- read.table(text =Lines, sep = ",", strip.white = TRUE, fill = NA)
    DF %>%
      mutate(id = 1:n()) %>%
      pivot_longer(-c(V1, id)) %>%
      drop_na %>%
      group_by(V1, id) %>%
      summarize(mean = mean(value), sd = sd(value)) %>%
      ungroup
    

    给予:

    # A tibble: 5 x 4
         V1    id  mean    sd
      <int> <int> <dbl> <dbl>
    1     0     1  824. 190. 
    2     0     2  914.  80.3
    3     1     3  839.  82.9
    4     2     4  879.  84.0
    5     2     5  898.  75.3
    

    2) Base R 使用 (1) 中的 DF 使用 reshape 重塑为长格式,使用 na.omitaggregate 删除 NA:

    DF2 <- na.omit(reshape(DF, dir = "long", varying = list(2:ncol(DF))))
    aggregate(V2 ~ V1 + id, DF2, function(x) c(mean = mean(x), sd = sd(x)))
    

    给予:

      V1 id   V2.mean     V2.sd
    1  0  1 823.60000 190.24800
    2  0  2 913.55556  80.28404
    3  1  3 839.20000  82.88667
    4  2  4 879.11111  83.95750
    5  2  5 898.28571  75.28770
    

    注意

    Lines <- "
    0, 980, 888, 720,987,543
    0, 880, 999, 820,990,888, 980, 898, 780,987
    1, 945, 856, 767,745,883
    2, 780, 899, 920,890,988, 780, 998, 870,787
    2, 800, 900, 822,999,880, 988, 899"
    

    【讨论】:

    • 那只是为了让它保持自包含和可重复性。假设格式相同,您将使用 read.table("MyData.csv", ...etc...)
    【解决方案2】:

    这是一个简单的基础 R 解决方案:

    #read file line by line
    textfile<-read.table("soquestion.txt", sep = ",", strip.white = TRUE)
    
    #find statistics
    mean_TS<-rowMeans(textfile[, 2:ncol(textfile)], na.rm=TRUE)
    SD_TS <- apply(textfile[, 2:ncol(textfile)], 1, function(x) {sd(x, na.rm=TRUE)})
    
    answer<-cbind(label=textfile[,1], mean_TS, SD_TS, textfile[,-1])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-16
      • 1970-01-01
      相关资源
      最近更新 更多