Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在R中计算一行中的相同响应_R - Fatal编程技术网

在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