【问题标题】:How to change the value of a specific column of multiple dataframes to the value of the dataframes' names themselves?如何将多个数据框的特定列的值更改为数据框名称本身的值?
【发布时间】:2020-03-15 08:35:20
【问题描述】:

所以我有一个包含多个数据集的列表。它们每个都有一个名为 Index 的列,其值为 NA。 现在我需要知道的是如何遍历列表,或者创建一个函数,为每个索引列分配特定数据集的名称?

到目前为止,我尝试做的事情如下:

ProductionIowa = read.csv("../Data/Production/ProductionIowa.csv")
ProductionIllinois = read.csv("../Data/Production/ProductionIllinois.csv")
ProductionNebraska = read.csv("../Data/Production/ProductionNebraska.csv")

# preparing production data

keepList = c("Year", "County", "County.ANSI", "Value")
ProductionIowa = ProductionIowa %>%
  select(keepList)
ProductionIllinois = ProductionIllinois %>%
  select(keepList)
ProductionNebraska = ProductionNebraska %>%
  select(keepList)


setwd("../Data/CountiesIowa/")

filenames <- gsub("\\.csv$","", list.files(pattern="\\.csv$"))

for(i in filenames){
  assign(i, read.csv(paste(i, ".csv", sep="")))
}

dfs <- Filter(function(x) is(x, "data.frame"), mget(ls()))
dfs = dfs[-c(81,82,83)]
names = str_to_upper(str_sub(filenames,0,-7))
res = lapply(dfs, transform, Index = NA)
names = list(names) 

非常沮丧,感谢任何帮助,谢谢。

【问题讨论】:

    标签: r function loops csv


    【解决方案1】:

    如果您想将列索引替换为数据集的名称,您可以使用for 循环:

    name_dataset = list.files(path= "../Data/Production",pattern = ".csv")
    setwd("../Data/Production")
    
    for(i in 1:length(name_dataset)
    {
       data = read.table(name_dataset[i],header = T)
       data$Index = name_dataset[i]
       write(data, name_dataset[i], sep = "\t")
    }
    

    这是你要找的吗?

    【讨论】:

      猜你喜欢
      • 2022-01-05
      • 2022-01-09
      • 1970-01-01
      • 2020-07-19
      • 2020-04-14
      • 2020-10-18
      • 1970-01-01
      • 1970-01-01
      • 2021-08-28
      相关资源
      最近更新 更多