逗号的意义? R编程

时间:2015-12-26 20:07:17

标签: r comma

在Coursera的R课程中分配1之前执行练习作业。

练习作业显示[," Day"],但我发现[" Day"]获得相同的结果。为什么他们在列标题之前加上逗号" Day"?

> andy[which(andy[, "Day"] == 30), "Weight"]   
[1] 135   
> andy[which(andy["Day"] == 30), "Weight"]    
[1] 135

附加信息 - 结构(str)

> str(andy)  
'data.frame':   30 obs. of  4 variables:  
 $ Patient.Name: Factor w/ 1 level "Andy": 1 1 1 1 1 1 1 1 1 1 ...  
 $ Age         : int  30 30 30 30 30 30 30 30 30 30 ...  
 $ Weight      : int  140 140 140 139 138 138 138 138 138 138 ...  
 $ Day         : int  1 2 3 4 5 6 7 8 9 10 ...  

1 个答案:

答案 0 :(得分:0)

这是一个小小的"备忘单"这可能有助于理解子集data.frames和各个输出的类的不同方法。您询问有关所选列的矢量化版本的结果的逗号。不使用列将返回该列的data.frame版本。您也可以使用$表示法,就像我在下面所做的那样。

andy = data.frame(Day = c(1:30), Weight = round(rnorm(30, 138, 1), 0))
andy[which(andy["Day"] == 30), "Weight"]    
#[1] 138

andy[which(andy[,"Day"] == 30), "Weight"]   
#[1] 138

andy[which(andy$Day == 30), "Weight"]   
#[1] 138

andy$Weight[andy$Day == 30]
#[1] 138

andy$Weight[andy["Day"] == 30]
#[1] 138

andy$Weight[andy[,"Day"] == 30]
#[1] 138

subset(andy, andy$Day == 30)$Weight
#[1] 138

subset(andy, andy$Day == 30)["Weight"]
#   Weight
#30    138

subset(andy, andy$Day == 30)[,"Weight"]
#[1] 138

class(andy["Day"])
#[1] "data.frame"

andy["Day"]
#    Day
# 1    1
# 2    2
# 3    3
...

class(andy[,"Day"])
#[1] "integer"

andy[,"Day"]
#[1]  1  2  3  4  5  6 ...

class(andy$Day)
#[1] "integer"

andy$Day
#[1]  1  2  3  4  5  6 ...