這是數據幀的一個子集我的工作:嵌套for循環中的數據幀。 <0 rows>(或0長度row.names)錯誤
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 = " ")
}
}
問題:<0 rows> (or 0-length row.names)
用於PP,AA,PA和AP:上面的for循環,但在此之外嵌套作品環路我收到以下消息腳本。爲什麼在這種情況下子數據集(PP,AA,PA和AP)是空的?
你需要做'PP < - dataframe [dataframe [[fruit]] =='2'&dataframe [[veg]] =='2',]'etc,dataframe $ fruit不是列 –
有一個關閉'''在計算'FRUIT'和'VEG'時太多了 – Acarbalacar