Reputation: 31
So I have this data :
data<-as.data.frame(matrix(1:9,ncol=3))
which gives this :
| V1 | V2 | V3 |
________________
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
I want to create a variable for each column to get this :
> V1
[1] 1 2 3
> V2
[1] 4 5 6
> V3
[1] 7 8 9
I know that if I do a loop with the assign function :
for (i in 1:length(data)) {
assign(names(data[i]),data[,i])
}
it works. But if I try with the "<-" :
for (i in 1:length(data)) {
names(data[i])<-data[,i]
}
it does not work. Why does it work with the assign function but not with the "<-" ?
Upvotes: 2
Views: 75
Reputation: 2301
You can also use lapply
to keep your vectors as a list. (Easier to reference):
nrows <- nrow(data)
nrows
3
vecs <- lapply(1:nrows, function(x) data[x, ])
vecs
[[1]]
V1 V2 V3
1 1 4 7
[[2]]
V1 V2 V3
2 2 5 8
[[3]]
V1 V2 V3
3 3 6 9
Upvotes: 1
Reputation: 887158
We can use list2env
list2env(data, .GlobalEnv)
-check for objects
V1
#[1] 1 2 3
V2
#[1] 4 5 6
V3
#[1] 7 8 9
In the for
loop, it can be looped over the column names and use assign
for(nm in names(data)) assign(nm, data[[nm]])
The names
assignment works only for assigning the column names or names
attribute of a vector
and not create an object. The error is basically about the difference in length
of the lhs
and rhs
of the assignment (<-
) operator
names(data[1])
#[1] "V1"
Better would be
names(data)[1]
and
data[,1]
#[1] 1 2 3
is the value of the column which is of length
3
when we assign <-
) it to the names(data)[1]
, it is assigning the first column name to 1 2 3
which differs in length
names(data)[1] <- data[,1]
Warning message: In names(data)[1] <- data[, 1] : number of items to replace is not a multiple of replacement length
returns a warning, but if we use the OP's method of subsetting
names(data[1]) <- data[,1]
Error in names(data[1]) <- data[, 1] : 'names' attribute [3] must be the same length as the vector [1]
Upvotes: 1