我正在为一个子集功能而苦苦挣扎,希望我能从云端得到一些帮助。
在我的数据集中,surveydata
可以找到列landscape
。我需要选择两种类型的所有景观7
,并5
与随机选择50
从每个景观类型的对象3
和6
。然后我想创建一个sub
在surveydata
数据框中调用的新变量,它应该包含一个数字,例如,1
如果在上一个选择中选择了对象,0
(或NA
)如果不是。
最好我搜索一个基本的 R 解决方案,但我不坚持。
我提供了一个随机数据集以便更好地理解。
#create data
surveydata <- as.data.frame(replicate(6,sample(0:1,1000,rep=TRUE)))
# change values of columns
surveydata$V3 <- sample(7, size = nrow(surveydata), replace = TRUE)
surveydata$V4 <- sample(5, size = nrow(surveydata), replace = TRUE)
surveydata$V5 <- sample(5, size = nrow(surveydata), replace = TRUE)
surveydata$V6 <- sample(5, size = nrow(surveydata), replace = TRUE)
#create column with same distribution of values
surveydata$group <- c(1,2)
# rename columns
colnames(surveydata)[1] <- "gender"
colnames(surveydata)[2] <- "expert"
colnames(surveydata)[3] <- "landscape"
colnames(surveydata)[4] <- "q1"
colnames(surveydata)[5] <- "q2"
colnames(surveydata)[6] <- "q3"
这是一个 R 方法,它使用采样和索引来实现结果:
# Sample index of rows where landscape is 3 or 6
ss <- sample(with(surveydata, which(landscape == 6 | landscape == 3)), 50, FALSE)
# Append index of all rows where landscape is 5 or 7
ss <- c(ss, with(surveydata, which(landscape == 5 | landscape == 7)))
# Create subset data frame
subset <- surveydata[ss, ]
# Create sub column to show which rows have been sampled
surveydata$sub <- numeric(nrow(surveydata))
surveydata$sub[ss] <- 1
# test result of creating sub column
head(surveydata)
#> gender expert landscape q1 q2 q3 group sub
#> 1 0 1 7 1 5 3 1 1
#> 2 1 1 5 2 2 3 2 1
#> 3 0 0 4 5 5 2 1 0
#> 4 0 0 3 5 5 4 2 0
#> 5 0 1 7 1 5 1 1 1
#> 6 1 0 7 5 1 1 2 1
# ensure subsetted data frame is as expected
head(subset)
#> gender expert landscape q1 q2 q3 group
#> 348 0 0 6 5 4 2 2
#> 333 1 1 6 4 2 4 1
#> 521 1 0 6 1 5 5 1
#> 522 1 0 6 4 5 2 2
#> 563 0 1 6 2 4 2 1
#> 13 0 0 6 5 2 4 1
由reprex 包(v0.3.0)于 2020 年 7 月 8 日创建
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句