我尝试在以下示例数据集中的多个列上应用else if函数:
dput(data_compressed)
structure(list(Day = c(0, 1, 0, 1, 1, 0, 1, 0, 1, 0), act1_001 = c("leisure",
"leisure", "leisure", "leisure", "leisure", "leisure", "leisure",
"leisure", "leisure", "leisure"), act1_002 = c("leisure", "leisure",
"leisure", "leisure", "leisure", "leisure", "leisure", "leisure",
"leisure", "leisure"), act1_003 = c("leisure", "leisure", "leisure",
"leisure", "leisure", "leisure", "leisure", "leisure", "leisure",
"leisure"), act1_004 = c("leisure", "leisure", "leisure", "leisure",
"leisure", "leisure", "leisure", "leisure", "leisure", "leisure"
), act1_005 = c("leisure", "leisure", "leisure", "leisure", "leisure",
"leisure", "leisure", "leisure", "leisure", "leisure")), row.names = c(NA,
-10L), class = c("tbl_df", "tbl", "data.frame"))
字符串
我的其他代码的逻辑:如果两个条件(i)Day=1和(ii)以“act1”开头的每一列都用“leisure”编码,则打印“leisure1”。如果Day=0且act1=leisure,则打印“leisure0”。相同的逻辑适用于其余语句。
library(dplyr)
library(tidyverse)
if(data$Day == 1 & data$across(starts_with("act1")) == "leisure") {
print("leisure1")
} else if(
data$Day == 0 & data$across(starts_with("act1")) == "leisure") {
print("leisure0")
} else if(
data$Day == 1 & data$across(starts_with("act1")) == "work") {
print("work1")
} else if(
data$Day == 0 & data$across(starts_with("act1")) == "work") {
print("work0")
} else if(
data$Day == 1 & data$across(starts_with("act1")) == "home") {
print("home1")
} else {
print("home0")
}
型
这是错误消息:
警告:未知或未初始化的列:across
。错误:尝试应用非函数
3条答案
按热度按时间lb3vh1jj1#
也许你只是这个意思。
字符串
数据
型
eimct9ow2#
从你的逻辑判断,你想在每一列中折叠与
Day
相关的数字和字母。要在基数R中做到这一点,你可以这样做:字符串
输出量:
型
yr9zkbsy3#
您使用的across不正确。下面是
tidyverse
中使用case_when()
的解决方案:字符串
数据类型:
型