【问题标题】:How to use substr function to multiple variables and write it a csv file in R?如何对多个变量使用 substr 函数并将其写入 R 中的 csv 文件?
【发布时间】:2017-05-05 13:01:32
【问题描述】:

有一个数据框,比如说 mtcars,我想从不同的变量中提取不同的值,最后我想在 R 中形成一个 CSV 数据框。

数据

   mpg      cyl   disp  hp 
   21.0   6160.0  110   3.90 
   21.0   6160.0  110   3.90 
   22.8   4108.0  93    3.85 
   21.4   6258.0  110   3.08 
   18.7   8360.0  175   3.15 

所以我想从 mpg 变量中提取第一个 2 个字母,从 cyl 中我想提取前 3 个数字.....等等,为此我有一个如下键

密钥文件

 header  startkey endkey
 mpg     0        2
 cyl     0        3
 disp    1        2
 hp      2        4

预期输出

   mpg  cyl   disp   hp 
   21   616   11    .90 
   21   616   11    .90 
   22   410   93    .85 
   21   625   11    .08 
   18   836   17    .15    

试过了:

vars = unique(as.character(keyfile$header))
start_keys = keyfile$startkey
end_keys = keyfile$endkey

for(i in 1:length(vars)){
for (j in 1:length(start_key)){
for(k in 1:length(end_key)){
data = substr(data$i,j,k)
filename = paste(deparse(substitute(output_data)), ".csv",sep="")
write.csv(data,file = filename)
}
}
}

请帮帮我

【问题讨论】:

    标签: r csv


    【解决方案1】:

    我们可以使用Map根据'keyfile'中对应的'startkey'、'endkey'提取'data'中每一列的子串

    data[] <- Map(substr, data[keyfile$header], keyfile$startkey, keyfile$endkey)
    

    如果我们想转换为numeric

    data[] <- Map(function(...) as.numeric(substr(...)), 
                   data[keyfile$header], keyfile$startkey, keyfile$endkey)
    data
    #  mpg cyl disp   hp
    #1  21 616   11 0.90
    #2  21 616   11 0.90
    #3  22 410   93 0.85
    #4  21 625   11 0.08
    #5  18 836   17 0.15
    

    数据

    data <- structure(list(mpg = c(21, 21, 22.8, 21.4, 18.7), cyl = c(6160, 
    6160, 4108, 6258, 8360), disp = c(110L, 110L, 93L, 110L, 175L
    ), hp = c(3.9, 3.9, 3.85, 3.08, 3.15)), .Names = c("mpg", "cyl", 
    "disp", "hp"), class = "data.frame", row.names = c(NA, -5L))
    
    keyfile <- structure(list(header = c("mpg", "cyl", "disp", "hp"), startkey = c(0L, 
    0L, 1L, 2L), endkey = c(2L, 3L, 2L, 4L)), .Names = c("header", 
    "startkey", "endkey"), class = "data.frame", row.names = c(NA, 
    -4L))
    

    【讨论】:

      猜你喜欢
      • 2014-12-29
      • 2018-05-22
      • 1970-01-01
      • 2021-11-01
      • 2019-03-03
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多