[英]Apply ifelse function to a list of dataframes in R
我是使用 R 的新手,这可能是一个非常基本的问题。 我在一个文件夹中有一些文件(8 个文件),我使用 list.files() 将所有文件放在一起。 作为结果,我获得了数据框列表。 我现在的目标是将每个文件的名称添加为新列。 我在路径“C:/test”中工作,所以每个文件都有以下全名:
> print(filesinfolder)
[1] "C:/test/alhamilla.csv" "C:/test/amo.csv" "C:/test/falto.csv" "C:/test/fbajo.csv" "C:/test/fmedio.csv"
[6] "C:/test/G1.csv" "C:/test/G2.csv" "C:/test/G3.csv"
我使用 str_sub() 来捕获每个文件路径的最后一个字符,然后我尝试在循环中应用和 ifelse function 以更正列表中所有元素的列的名称。 但是,尽管 R 花费了时间处理,但它没有显示任何错误,但也没有应用我的 ifelse 语句。 对正在发生的事情有任何想法吗?
数据链接: https://drive.google.com/drive/folders/1Kr0nGPvgQThcmmgKIMVFHrkjHxhnJNqg?usp=sharing
谢谢您的帮助!!
##Read files in the folder:
filesinfolder <- list.files("C:/test",pattern="*.csv",full.names=TRUE)
files <- lapply(filesinfolder, read.csv, sep = ",")
names(files) <- substr(filesinfolder, 1, 25)
#Add file names in a new colum starting by the end of the file name
for( i in seq_along(files)){
files[[i]]$Plot <- paste (str_sub(names(files)[[i]],-13,-1)) }
##Correct the names
for( i in seq_along(files)){
ifelse (files[[i]]$Plot == "alhamilla.csv", files[[i]]$Plot == "alhamilla", files[[i]]$Plot)
ifelse (files[[i]]$Plot == "/test/amo.csv", files[[i]]$Plot == "amoladeras", files[[i]]$Plot)
ifelse (files[[i]]$Plot == "est/falto.csv", files[[i]]$Plot == "falto", files[[i]]$Plot)
ifelse (files[[i]]$Plot == "est/fbajo", files[[i]]$Plot == "fbajo", files[[i]]$Plot)
ifelse (files[[i]]$Plot == "st/fmedio.csv", files[[i]]$Plot == "fmedio", files[[i]]$Plot)
ifelse (files[[i]]$Plot == "/test/G1.csv", files[[i]]$Plot == "G1", files[[i]]$Plot)
ifelse (files[[i]]$Plot == "/test/G2.csv", files[[i]]$Plot == "G2", files[[i]]$Plot)
ifelse (files[[i]]$Plot == "/test/G3.csv", files[[i]]$Plot == "G3", files[[i]]$Plot)
}
我很确定有更漂亮的方法可以做到这一点,例如直接在map()
function 中重命名列,但这是我的建议
library(tidyverse)
list.files(pattern = "*.csv") %>%
map_dfr(~ read_csv(.) %>%
mutate(filename = .x %>%
str_remove_all("\\.csv"))) %>%
pivot_wider(names_from = filename,
values_from = NDVI) %>%
unnest(everything())
# A tibble: 9 x 8
alhamilla amo falto fbajo fmedio G1 G2 G3
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 0.134 0.171 0.455 0.577 0.307 0.477 0.340 0.339
2 0.0960 0.211 0.457 0.525 0.343 0.405 0.322 0.408
3 0.107 0.220 0.438 0.489 0.370 0.248 0.352 0.428
4 0.149 0.225 0.446 0.505 0.431 0.409 0.345 0.422
5 0.226 0.217 0.465 0.520 0.500 0.497 0.324 0.427
6 0.208 0.200 0.470 0.496 0.523 0.439 0.329 0.455
7 0.155 0.203 0.451 0.440 0.528 0.419 0.305 0.535
8 0.167 0.220 0.436 0.420 0.536 0.413 0.339 0.527
9 0.173 0.231 0.330 0.429 0.488 0.377 0.363 0.419
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.