dataframe
対応する行の値内の値に応じて新しい列を追加する既存のRに新しい列を追加しようとしています。値が1
新しい場合、値にはone
、が含まれる必要があります。値が2
新しい場合、値にはtwo
、が含まれる必要があります。それ以外の場合。three or more
このコード:
mydf <- data.frame(a = 1:6,
b = rep("reproducible", 6),
c = rep("example", 6),
stringsAsFactors = FALSE)
mydf
レンダリング:
コードの使用:
mydf["encoded"] <- { if (mydf['a'] == 1) 'one' else if (mydf['a'] == 2) 'two' else 'three or more' }
mydf
レンダリング:
警告も生成されます:
Warning message in if (mydf["a"] == 1) "one" else if (mydf["a"] == 2) "two" else "three or more":
“the condition has length > 1 and only the first element will be used”
新しい列がに追加されdataframe
ますが、すべての値は同じです:one
新しい列の値を正しく追加するロジックを実装していませんか?
使用するソリューションdplyr::case_when
:
構文とロジックは自明である:場合a
と同じである1
- encoded
「1」に等しいです。場合a
と同じである2
- encoded
「2」に等しいです。他のすべての場合-エンコードは「3つ以上」に等しい。
そしてmutate
、新しい列を作成するだけです。
library(dplyr)
mutate(mydf, encoded = case_when(a == 1 ~ "one",
a == 2 ~ "two",
TRUE ~ "three or more"))
a b c encoded
1 1 reproducible example one
2 2 reproducible example two
3 3 reproducible example three or more
4 4 reproducible example three or more
5 5 reproducible example three or more
6 6 reproducible example three or more
使用するソリューションbase::ifelse
:
mydf$encoded <- ifelse(mydf$a == 1,
"one",
ifelse(mydf$a == 2,
"two",
"three or more"))
あなたがmydf$a
複数回書くのが好きでないならば、あなたは使うことができますwith
:
mydf$encoded <- with(mydf, ifelse(a == 1,
"one",
ifelse(a == 2,
"two",
"three or more")))
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加