【问题标题】:Transforming variables of dataframes stored in a list转换存储在列表中的数据帧的变量
【发布时间】:2015-09-16 20:18:13
【问题描述】:

我有一个数据框列表,所有数据框都具有相同的结构,我使用以下代码创建:

myfiles <- list.files(patter='.csv')
mydata <- lapply(myfiles, read.csv)
names(mydata) <- gsub("\\.csv", "", myfiles)

我必须对列表中的每个数据框进行一系列计算。但首先我必须转换某些变量的数据类型。我一直在寻找答案,但一直没有找到答案。我得到的关闭是:

lapply(mydata, function(i) {
transform(mydata, PIN=as.character(PIN), Class=as.character(Class), TaxStatus=as.character(TaxStatus), TaxcCode=as.character(TaxCode), TaxRate(as.doublt(TaxRate) *.001), Amt1=(as.double(Amt1) *.01), Amt2=(as.double(Amt2) * .01))
})

但是当我运行它时,我收到以下错误:

data.frame 中的错误(PropTax1993 = 列表(PIN = c(1011000020000, 1011000030000, : 参数暗示不同的行数:1443916、1449711、1459247、1469691、1480347、1491574、1504263、1516502、1530584

我认为这是因为我列表中的数据框长度不同。我也试过:

lapply(1:length(mydata), function(i) {
transform(mydata, PIN=as.character(PIN), Class=as.character(Class), TaxStatus=as.character(TaxStatus), TaxcCode=as.character(TaxCode), TaxRate(as.doublt(TaxRate) *.001), Amt1=(as.double(Amt1) *.01), Amt2=(as.double(Amt2) * .01))
})

...但这也不起作用。我对 R (和一般编程)比较陌生。任何帮助将不胜感激。

【问题讨论】:

  • 使用transform(i, PIN=as.character(.. 而不是“mydata”。还有一个等号并修复TaxRate=(as.double(TaxRate)*.001)之类的错字
  • 工作就像一个魅力!非常感谢皮埃尔。

标签: r transform lapply


【解决方案1】:

不是最优雅的解决方案,使用其中一个 apply 函数可能很可能(这对于更优化的解决方案会更好),但这是我刚刚制定的 for 循环解决方案,应该可以解决问题:

# Creating sample data frames (all the same content).
myDF <- data.frame(a = seq(1, 50), b = seq(1, 100, 2) , c = seq(1, 200, 4))
myDF2 <- myDF
myDF3 <- myDF

# Creating a sample list of those data frames.
myList <- list(myDF, myDF2, myDF3)

# The data is in integer form.
print(class(myList[[1]]$a))

# Looping through each data frame in the list and changing each the same way.
for(item in 1:length(myList)) {

  myList[[item]]$a <- as.character(myList[[item]]$a) # Coercing the data type of each column here.
  myList[[item]]$b <- as.character(myList[[item]]$b)
  myList[[item]]$c <- as.character(myList[[item]]$c)

}

# The data is now in character form.
print(class(myList[[1]]$a)) 

只需更改 for 循环中的列名(a、b 和 c)以及用于强制列的函数。

还要注意双括号[[1]] 表示法对于从列表中提取数据是特殊的。对于向量或数组,它只是一个括号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 2013-11-16
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    相关资源
    最近更新 更多