我有一个数据框:
set.seed(1)
My_DF <- cbind(paste0("Project",1:10),rnorm(10))
colnames(My_DF) <- c( "Projeck_Name","Values")
My_DF
Projeck_Name Values
[1,] "Project1" "-0.626453810742332"
[2,] "Project2" "0.183643324222082"
[3,] "Project3" "-0.835628612410047"
[4,] "Project4" "1.59528080213779"
[5,] "Project5" "0.329507771815361"
[6,] "Project6" "-0.820468384118015"
[7,] "Project7" "0.487429052428485"
[8,] "Project8" "0.738324705129217"
[9,] "Project9" "0.575781351653492"
[10,] "Project10" "-0.305388387156356"
我希望在第一列中将第二列指定为变量的值。换句话说,Project1将是一个包含值"-0.62645"
:
assign(My_DF[1,1],My_DF[1,2])
我想为所有项目执行此操作:
for(i in 1:length(My_DF[,1])) {
assign(My_DF[i,1],My_DF[i,2])
}
有没有办法在没有'for'循环的情况下以有效的方式完成它?
感谢您的帮助!
答案 0 :(得分:1)
不要在工作区中创建10个对象,而是将它们保存在命名的列表中。
# example dataframe
set.seed(1); My_DF <- data.frame(Projeck_Name = paste0("Project",1:10), Values = rnorm(10))
# keep each project value in a list
allProjects <- as.list(setNames(My_DF$Values, My_DF$Projeck_Name))
allProjects$Project1
# [1] -0.6264538
答案 1 :(得分:0)
这将创建10个新变量Project1
,Project2
等。
txt <- paste(df$Project_Name, "<-", df$Values, sep="")
eval(parse(text=txt))
Project1
[1] -0.6264538
Project2
[1] 0.1836433
示例数据:
set.seed(1)
df <- data.frame(Project_Name=paste0("Project",1:10), Values=rnorm(10))