【发布时间】:2016-11-17 10:40:16
【问题描述】:
这是我正在处理的数据框的一个子集:
ID FRUIT1 FRUIT2 FRUIT3 VEG1 VEG2 VEG3 1 1 2 2 1 2 2 2 2 1 1 1 1 1 3 2 1 2 1 2 2 4 2 2 2 1 2 1 5 1 1 1 2 1 2
它由 5 个科目组成,其中有 3 种水果和 3 种蔬菜的信息:
- 1 = 对象不吃水果/蔬菜
- 2 = 对象吃水果/蔬菜
我有兴趣计算有多少人食用了 9 种可能的水果和蔬菜组合(FRUIT1 和 VEG1,FRUIT1 和 VEG2,……)。 这是我写的脚本:
# Read data
dataframe <- read.csv("myfile.csv", header=TRUE)
# Define variables
FRUIT= names(dataframe)[2:4])
VEG= names(dataframe[5:7]))
# Check frequency of interactions
for (fruit in FRUIT) {
for (veg in VEG) {
#Double-positive: keep only subjects that each both the fruit and the vegetable
PP <- dataframe[dataframe$fruit=='2' & dataframe$veg=='2',]
#Double-negative: keep only subjects that don’t eat any
AA <- dataframe[dataframe$fruit=='1' & dataframe$veg=='1',]
#Only FRUIT-positive: keep only subjects that eat the fruit, but not the vegetable
PA <- dataframe[dataframe$fruit=='2' & dataframe$veg=='1',]
#Only VEG-positive: keep only the subject that eat the vegetable, but not the fruit
AP <- dataframe[dataframe$fruit=='1' & dataframe$veg=='2',]
# Print the name of the fruit, the vegetable, and the counts of each of the 4 categories
toprint <- c(kir,hla,nrow(PP),nrow(AP),nrow(PA),nrow(AA))
setwd(“~/Directory/“)
write(toprint, file = "NumberIndividuals.csv",ncolumns=6,append = TRUE, sep = " ")
}
}
问题:上面的脚本在 for 循环之外工作,但在这个嵌套的 for 循环中,我收到以下消息:<0 rows> (or 0-length row.names) 用于 PP、AA、PA 和 AP。为什么在这种情况下子数据集(PP、AA、PA 和 AP)是空的?
【问题讨论】:
-
你需要做
PP <- dataframe[dataframe[[fruit]] == '2' & dataframe[[veg]] == '2',]等,dataframe$fruit不是列 -
在您对
FRUIT和VEG的计算中,有一个关闭的)过多
标签: r dataframe subset two-columns