![](/img/trans.png)
[英]R - Add columns to dataframes in list by looping through elements in a vector
[英]R: Looping through list of dataframes in a vector
我有一個數據集,我只想一次遍歷數據框中的某些列來創建一個圖形。 我的數據框的結構包含我從較大的數據集解析為包含多個數據框的向量的數據。
我想從向量的一個數據幀中調用一列。 我想循環在數據框上調用每一列。
請參見下面的示例:
d1 <- data.frame(y1=c(1,2,3),y2=c(4,5,6))
d2 <- data.frame(y1=c(3,2,1),y2=c(6,5,4))
my.list <- list(d1, d2)
我要做的就是my.list
我該怎么做?
您不需要for循環即可獲取其數據點。 您可以通過其列名稱來調用該列。
# a toy dataframe
d <- data.frame(A = 1:20, B = sample(c(FALSE, TRUE), 20, replace = TRUE),
C = LETTERS[1:20], D = rnorm(20, 0, 1))
col_names <- c("A", "B", "D") # names of columns I want to get
d[,col_names] # returns a dataset with the values of the columns you want
這是使用for循環解決問題的方法:
# a toy dataframe
mylist <- list(dat1 = data.frame(A = 1:20, B = LETTERS[1:20]),
dat2 = data.frame(A = 21:40, B = LETTERS[1:20]),
dat3 = data.frame(A = 41:60, B = LETTERS[1:20]))
col_names <- c("A") # name of columns I want to get
for (i in 1:length(mylist)){
# you can do whatever you want with what is returned;
# here I am just print them out
print(names(mylist)[i]) # name of the data frame
print(mylist[[i]][,col_names]) # values in Column A
}
我認為您問題的最簡單答案是使用雙括號。
for (i in 1:length(my.list)) {
print(my.list[[i]]$column)
}
假設數據框列表中的所有列都具有相同的名稱,則該方法有效。 如果需要,您還可以在數據框中調用列的位置。
是的,lapply可能更優雅,但是在某些情況下,for循環更有意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.