I have a list of 52 datasets that are between 5 and 6 rows; they will all need an added column but to add this column the row number needs to be the same. To the sets with 5 rows, I want to add a 6th row with "NA" filling the row as a place holder. Here is where I have started, but I am unsure how to complete the loop because I am unsure what to use for the "df" in the nrow() function. I want this to do nothing to the datasets with 6 rows already.
testrows<-if lapply(listallht_allwk, nrow) = 5 {
df[nrow(df) 1 ,] <- NA
}
CodePudding user response:
Data
Here I've created two dummy data frames for demonstration.
df <- data.frame(row = 1:5, col1 = LETTERS[1:5])
df2 <- data.frame(row = 1:6, col1 = LETTERS[1:6])
df_list <- list(df, df2)
df_list
[[1]]
row col1
1 1 A
2 2 B
3 3 C
4 4 D
5 5 E
[[2]]
row col1
1 1 A
2 2 B
3 3 C
4 4 D
5 5 E
6 6 F
Code
It might be better to use if else
inside lapply
. Simply rbind
the dataframe with NA
to get an extra row of NA
.
lapply(df_list, function(x) {
if (nrow(x) == 5) {
rbind(x, NA)
} else {
x
}
})
[[1]]
row col1
1 1 A
2 2 B
3 3 C
4 4 D
5 5 E
6 NA <NA>
[[2]]
row col1
1 1 A
2 2 B
3 3 C
4 4 D
5 5 E
6 6 F