R 如何使用真/假信息计算条件和?
根据第3列和第4列中的真/假值,我很难计算出数值分割的代码:(col1)/(col2) 我有500行数据,我试图根据不同的条件计算作物的平均产量(kg作物/公顷)。我试图回答这样一个问题:“如果第3列的条件为真,第4列的条件为假,那么平均收益率是多少?” 编辑:下面是示例数据R 如何使用真/假信息计算条件和?,r,R,根据第3列和第4列中的真/假值,我很难计算出数值分割的代码:(col1)/(col2) 我有500行数据,我试图根据不同的条件计算作物的平均产量(kg作物/公顷)。我试图回答这样一个问题:“如果第3列的条件为真,第4列的条件为假,那么平均收益率是多少?” 编辑:下面是示例数据 col 1 col2 col 3 col4 1.5 2.0 T T 1.5 2.0 F T 2.5 5.0 F F 2.5
col 1 col2 col 3 col4
1.5 2.0 T T
1.5 2.0 F T
2.5 5.0 F F
2.5 5.0 F T
所以我试图找到col1/col2的平均值,例如,col3=F和col4=T
谢谢大家! 您需要根据这两个条件对数据进行子集。您可以使用
[col3&!col4]
执行此操作,如下所示:
mean(with(data,col1[col3 & !col4]/col2[col3 & !col4]))
(with
是一种更简单的方法,不必每次都写数据$
)
例如,以下是一些虚假数据:
data<-data.frame(col1=1:5,col2=10:6,col3=c(TRUE,TRUE,TRUE,FALSE,FALSE),col4=c(FALSE,TRUE,FALSE,FALSE,TRUE))
下面是一个使用
tidyverse
的解决方案
n <- 100
df <- data.frame(
kg = runif(n),
ha = runif(n),
col3 = sample(c(TRUE,FALSE), n, TRUE),
col4 = sample(c(TRUE,FALSE), n, TRUE)
)
首先,我使用函数data.frame
创建一个可复制的数据集
n <- 100
df <- data.frame(
kg = runif(n),
ha = runif(n),
col3 = sample(c(TRUE,FALSE), n, TRUE),
col4 = sample(c(TRUE,FALSE), n, TRUE)
)
首先,我将创建一个可复制的数据集:
data<-data.frame("col1"=rnorm(500),"col2"=rnorm(500),
"col3"=c(rep(TRUE,250),rep(FALSE,250)),"col4"=c(rep(FALSE,250),rep(TRUE,250)))
这是问当数据的col3为真,而col4为假时,收益率是多少
但是,如果您想要所有可能的组组合的摘要,可以通过以下方式使用包dplyr
:
install.packages("dplyr") # This will have to be run only the first time you use the package on one machine
library(dplyr) # This code will need to be run every new R session
data %>% group_by(col3,col4) %>%
summarise(
MeanYield = mean(yield)
)
# A tibble: 2 x 3
# Groups: col3 [2]
col3 col4 MeanYield
<lgl> <lgl> <dbl>
1 FALSE TRUE 20.4
2 TRUE FALSE 1.93
install.packages(“dplyr”)#仅当您第一次在一台计算机上使用该软件包时,才必须运行该程序
库(dplyr)#此代码需要在每个新的R会话中运行
数据%>%分组依据(col3,col4)%>%
总结(
平均收益率=平均(收益率)
)
#一个tibble:2x3
#分组:col3[2]
col3 col4平均产量
1假-真20.4
2对错1.93
在本例中,只有两种可能性(col3=T&col4=F)和(col3=F&col4=T),但代码将提供所有可能性
- 作为一个补充:我知道负值对于作物或公顷可能没有意义,我只是在这里使用
来加快速度(尽管我的解释违背了快速的目的)rnorm
data$yield <- data$col1 / data$col2
head(data)
col1 col2 col3 col4 yield
1 0.8976488 0.006764518 TRUE FALSE 132.6996029
2 -0.2829754 0.980092790 TRUE FALSE -0.2887230
3 -0.2266733 1.285616004 TRUE FALSE -0.1763149
4 1.4690071 -0.297252879 TRUE FALSE -4.9419440
5 -0.1438242 0.917662116 TRUE FALSE -0.1567289
6 -1.3297183 -0.880964698 TRUE FALSE 1.5093889
mean(data$yield[data$col3==T & data$col4==F])
[1] 1.929354
install.packages("dplyr") # This will have to be run only the first time you use the package on one machine
library(dplyr) # This code will need to be run every new R session
data %>% group_by(col3,col4) %>%
summarise(
MeanYield = mean(yield)
)
# A tibble: 2 x 3
# Groups: col3 [2]
col3 col4 MeanYield
<lgl> <lgl> <dbl>
1 FALSE TRUE 20.4
2 TRUE FALSE 1.93