Reputation: 119
I have a list with 16 elements all having the same variables (31 columns). Now i want to make a few changes on this variables and hope that I can do them for each element of the list. Simplified the list looks like this
>list
>$`M2_2004`
> A B C
>1 2 1 3
>2 4 6 5
>3 6 4 0
...
>$`M2_2005`
> A B C
>70 5 9 1
>71 4 6 5
>72 2 5 8
...
For example, now i want to add 2 leading numbers to the columns B and C for each element of the list. This works with the following command
sprintf("%04d", B)
where B is the column. Since I am quite new to R, I would apply this to each column of each element with a seperate line of code, but i hope to speed up the process by doing this in a single command.
Upvotes: 1
Views: 45
Reputation: 51974
You can use lapply
to apply the same function to each element of a list, and sapply
to apply the same function to multiple columns of the same data frame:
lapply(your_list, function(x){
x[c("B", "C")] <- sapply(x[c("B", "C")], function(y) sprintf("%04d", y))
})
Upvotes: 1