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]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…