我在制作 ifelse / if_else 陳述句時遇到問題。我想創建一個新列“Transtyp”,如果“Plot”列具有奇數(1 或 3 或 5 或 7),則分配“2”,當“Plot”具有偶數時分配“5”數字。這是我的df
df <- structure(list(Soll = c("1189", "1189", "1189", "1189", "1189",
"1189", "1189", "1189", "1189", "1189", "1189", "1189", "1189",
"1189", "1189", "1189", "1189", "1189", "1189", "1189"), Datum = c("2021-03-15",
"2021-03-15", "2021-03-15", "2021-03-15", "2021-03-15", "2021-03-16",
"2021-03-16", "2021-03-16", "2021-03-16", "2021-03-16", "2021-03-17",
"2021-03-17", "2021-03-17", "2021-03-17", "2021-03-17", "2021-03-18",
"2021-03-18", "2021-03-18", "2021-03-18", "2021-03-18"), Plot = c(1,
4, 6, 7, 8, 1, 4, 6, 7, 8, 1, 4, 6, 7, 8, 1, 4, 6, 7, 8), Temp = c(21.4609852941176,
21.5064705882353, 21.4601323529412, 21.4587352941176, 21.4630147058824,
11.0828229166667, 11.03209375, 11.3093020833333, 11.2860833333333,
11.1405104166667, 2.1683125, 2.10675, 2.87871875, 2.84852083333333,
2.44628125, 1.41326041666667, 1.47109375, 1.66685416666667, 1.53930208333333,
1.34465625), RH = c(37.8671617647059, 37.8925, 38.0004411764706,
38.26425, 37.9111029411765, 62.1298645833333, 63.2143333333333,
62.1141666666667, 62.55275, 62.5445416666667, 92.7891041666667,
93.5631458333333, 91.8378333333333, 93.2626145833333, 92.565625,
92.7335625, 93.5223125, 92.7023541666667, 93.6509375, 93.120375
), Transtyp = c(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2)), row.names = c(NA, -20L), class = c("tbl_df",
"tbl", "data.frame"))
現在,我正在使用此代碼,但它僅在 Plot == 1 時分配“2”并忽略其余部分。我錯過了什么?
df %>% mutate(Plot = as.numeric(Plot)) %>%
mutate(Transtyp = ifelse(Plot == (1 | 3 | 5 | 7), "2", "5")) -> df_t
任何幫助表示贊賞!非常感謝!
uj5u.com熱心網友回復:
你要:
library(dplyr)
df %>% mutate(Transtyp = if_else(Plot %in% c(1, 3, 5, 7), "2", "5"))
# A tibble: 20 × 6
Soll Datum Plot Temp RH Transtyp
<chr> <chr> <dbl> <dbl> <dbl> <chr>
1 1189 2021-03-15 1 21.5 37.9 2
2 1189 2021-03-15 4 21.5 37.9 5
3 1189 2021-03-15 6 21.5 38.0 5
4 1189 2021-03-15 7 21.5 38.3 2
5 1189 2021-03-15 8 21.5 37.9 5
6 1189 2021-03-16 1 11.1 62.1 2
7 1189 2021-03-16 4 11.0 63.2 5
8 1189 2021-03-16 6 11.3 62.1 5
9 1189 2021-03-16 7 11.3 62.6 2
10 1189 2021-03-16 8 11.1 62.5 5
11 1189 2021-03-17 1 2.17 92.8 2
12 1189 2021-03-17 4 2.11 93.6 5
13 1189 2021-03-17 6 2.88 91.8 5
14 1189 2021-03-17 7 2.85 93.3 2
15 1189 2021-03-17 8 2.45 92.6 5
16 1189 2021-03-18 1 1.41 92.7 2
17 1189 2021-03-18 4 1.47 93.5 5
18 1189 2021-03-18 6 1.67 92.7 5
19 1189 2021-03-18 7 1.54 93.7 2
20 1189 2021-03-18 8 1.34 93.1 5
在 R 中,|指的是邏輯或,所以當你這樣做時1 | 3 | 5 | 7它會回傳TRUE。然后,當您嘗試將 Plot 與 TRUE 進行比較時,它將隱式轉換TRUE為1. 這就是為什么它沒有按照您的意愿行事:
> as.numeric(1 | 3 | 5 | 7)
[1] 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/351225.html
上一篇:sapply if-保留列名
