[英]Conditional calculations for rows in dataframe R
在我的“新”列中的數據集中,我想做以下事情:如果百分比大於 100%,我想從 200% 中減去該百分比,例如,如果值為 120%,我希望在行為 200%-120%,即 80%。 我怎樣才能做到這一點? 謝謝!
jointdataset1 <- structure(list(group = c("Interests", "Interests", "Interests",
"Interests", "Interests", "Interests", "Interests", "Interests",
"Interests", "Interests", "Interests", "Interests"), mean_name = c("Administrating processes",
"Analytical", "Art and Culture", "Commercial activities", "Creative",
"Helping/supporting", "Leading", "Networking", "Physical", "Practical",
"Technical", "Transforming Processes"), means.x = c(4, 4, 1,
4, 3, 3, 3, 3, 3, 6, 6, 1), means.y = c(4, 5.5, 1, 5, 3, 4, 4.5,
3.5, 2.5, 5.5, 6.5, 3), new = c("100.0%", "72.7%", "100.0%",
"80.0%", "100.0%", "75.0%", "66.7%", "85.7%", "120.0%", "109.1%",
"92.3%", "33.3%")), class = "data.frame", row.names = c(NA, -12L
))
這應該有效。
library(dplyr)
jointdataset1 %>%
select(!new) %>%
mutate(new = round(means.x/means.y*100, 1)) %>%
mutate(new = case_when(new > 100 ~ 200-new,
new <= 100 ~ new))
如果您希望“新”列仍然具有 % 符號,您可以執行以下操作:
library(dplyr)
jointdataset1 %>%
mutate(value = as.numeric(sub("\\%.*", "", new)),
new_value = ifelse(value > 100, 200 - value, value),
new = paste0(new_value,'%')) %>%
dplyr::select(c(-value, -new_value))
輸出:
group mean_name means.x means.y new
1 Interests Administrating processes 4 4.0 100%
2 Interests Analytical 4 5.5 72.7%
3 Interests Art and Culture 1 1.0 100%
4 Interests Commercial activities 4 5.0 80%
5 Interests Creative 3 3.0 100%
6 Interests Helping/supporting 3 4.0 75%
7 Interests Leading 3 4.5 66.7%
8 Interests Networking 3 3.5 85.7%
9 Interests Physical 3 2.5 80%
10 Interests Practical 6 5.5 90.9%
11 Interests Technical 6 6.5 92.3%
12 Interests Transforming Processes 1 3.0 33.3%
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.