Reputation: 39613
I have a little problem to solve in R. I have this list a1
in R:
> a1
[[1]]
x1 x2 x3
1 1 1 1
2 2 2 2
3 2 2 2
4 13 13 13
5 12 12 12
6 23 23 23
7 12 12 12
[[2]]
x1 x2 x3
1 2 2 2
2 2 2 2
3 2 2 2
4 13 13 13
5 12 12 12
6 23 23 23
7 12 12 12
[[3]]
x1 x2 x3
1 3 3 3
2 2 2 2
3 2 2 2
4 13 13 13
5 12 12 12
6 23 23 23
7 12 12 12
My problem is I don't get to extract all elements as data frames. For example I used this code for extract them as data frames but I got this error:
for(i in c(1:3))
{
paste("a",i)=as.data.frame(a1[i])
}
Error in paste("a", i) = as.data.frame(a1[i]) :
target of assignment expands to non-language object
My problem is the list has 20 elements and when I put a1=as.data.frame(a1[1])
it works but I would have to write many lines because the for
code showed doesn't work. Thanks for your help.
Upvotes: 1
Views: 155
Reputation: 121608
You should keep your elements in a list , Better to use lapply
to avoid the side effect . Try something like this for example:
lapply(a1,write.csv)
EDIT add flodel answer:
filenames <- paste0(seq_along(a1), ".csv")
mapply(write.csv, a1, file = filenames)
Upvotes: 1
Reputation: 193677
If I understand your goal correctly, two steps:
list2env
.Here's an example:
mylist <- list(data.frame(matrix(1:4, ncol = 2)),
data.frame(matrix(5:8, ncol = 2)),
data.frame(matrix(9:12, ncol = 2)))
names(mylist) <- LETTERS[seq_along(mylist)]
mylist
# $A
# X1 X2
# 1 1 3
# 2 2 4
#
# $B
# X1 X2
# 1 5 7
# 2 6 8
#
# $C
# X1 X2
# 1 9 11
# 2 10 12
A
# Error: object 'A' not found
list2env(mylist, envir=.GlobalEnv)
# <environment: R_GlobalEnv>
A
# X1 X2
# 1 1 3
# 2 2 4
Upvotes: 1