Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 使用循环从数据帧获取值_R_Loops - Fatal编程技术网

R 使用循环从数据帧获取值

R 使用循环从数据帧获取值,r,loops,R,Loops,我有一个dataframe x,它有3列5行 Group 1 Group 2 Group 3 brandA -1.4095 -0.9295 -0.6889 brandB -0.7400 -0.6498 -0.3269 brandC -1.7454 -0.9119 -0.8219 sizeM 0.5047 -3.4571 0.4003 sizeL -1.3012 -5.9978 -0.2422 我需要创建一个循环,以获得组1(-1.4)、组2(-0.9)和组

我有一个dataframe x,它有3列5行

        Group 1 Group 2 Group 3
brandA  -1.4095 -0.9295 -0.6889 
brandB  -0.7400 -0.6498 -0.3269
brandC  -1.7454 -0.9119 -0.8219 
sizeM    0.5047 -3.4571  0.4003
sizeL   -1.3012 -5.9978 -0.2422
我需要创建一个循环,以获得组1(-1.4)、组2(-0.9)和组3(-0.6)中brandA的b1。第1、2和3组的brandB为b2,b3组的brandB为b2。我试着用trivil get paste,但我不知道怎么做

for (i in 1:3) {
  b1 <- get(paste("x"))[['Group', sep=""]] 
}
for(1:3中的i){

b1使用
by
将数据框按行拆分并取消列出以创建命名向量。
setNames
是将列表名称更改为所需名称,然后使用
list2env
将列表中的每个元素构建到全局环境中。请注意
b1
~
b3
是命名向量,而不是具有一个r的数据框噢

lst <- setNames(by(df[1:3,], 1:3, unlist), paste0("b", 1:3))
list2env(lst, .GlobalEnv)

b1
#  Group1  Group2  Group3 
# -1.4095 -0.9295 -0.6889

b2
#  Group1  Group2  Group3 
# -0.7400 -0.6498 -0.3269

b3
#  Group1  Group2  Group3 
# -1.7454 -0.9119 -0.8219 

lst因此需要一个向量
c(“Group1(-1.4095)”,“Group1(-0.9295)”,…)
每行?请包括您对第1行的预期输出。实际上,我想为每个组分别获得b。请澄清……什么是
b
?添加您的预期输出。您希望输出的结构如何?我想我必须根据组将数据框拆分为列表。因此,输出应该是列表y1、y2、y3
df <- structure(list(Group1 = c(-1.4095, -0.74, -1.7454, 0.5047, -1.3012),
    Group2 = c(-0.9295, -0.6498, -0.9119, -3.4571, -5.9978),
    Group3 = c(-0.6889, -0.3269, -0.8219, 0.4003, -0.2422)),
  class = "data.frame", row.names = c("brandA", "brandB", "brandC", "sizeM", "sizeL"))