在R中计算一行中的相同响应
我有一个如下的数据框在R中计算一行中的相同响应,r,R,我有一个如下的数据框 multi_df <- data.frame( food=c("A","B","C"), education=c("A","B","D"), health=c("F","C","A")
multi_df <- data.frame( food=c("A","B","C"),
education=c("A","B","D"),
health=c("F","C","A")
)
multi_df编写一个函数来计算行中最高频率值的比率,并相应地返回文本
check_response <- function(x) {
n <- sort(table(x), decreasing = TRUE)[1]
if(n/length(x) > 0.5) "more than 50% response is same" else "not same response"
}
或使用dplyr
:
library(dplyr)
multi_df %>%
rowwise() %>%
mutate(flag = check_response(c_across()))
# food education health flag
# <chr> <chr> <chr> <chr>
#1 A A F more than 50% response is same
#2 B B C more than 50% response is same
#3 C D A not same response
库(dplyr)
多功能df%>%
行()
mutate(flag=check\u response(c\u cross()))
#食物教育及健康旗
#
#1超过50%的响应是相同的
#2 B C超过50%的响应是相同的
#3 C D不一样的回答
非常感谢你,兄弟,我欠你一杯咖啡,如果我只取上面数据框的两列,即食物和教育,我能做同样的事吗?是的,你能做多谢兄弟
multi_df$flag <- apply(multi_df, 1, check_response)
library(dplyr)
multi_df %>%
rowwise() %>%
mutate(flag = check_response(c_across()))
# food education health flag
# <chr> <chr> <chr> <chr>
#1 A A F more than 50% response is same
#2 B B C more than 50% response is same
#3 C D A not same response