我有一個包含多個變數的表。其中一個變數是其他實驗室進行的一項研究的參與者的性別列。問題是,Sex 有時被定義為 F、FEMALE 或女性,男性也是如此。我需要使用 plyr 包(我知道它很老)->mapvalues函式,讓所有女性都在 F 下,所有男性都在 M 下。這是資料框,它非常基本
mre_data <- structure(list(name = c("John", "Clara", "Smith", "Ray", "karen", "Ruba", "Josh", "Jennifer", "David", "Maria", "Sam"),
sex = c("Male", "F", "MALE", "M", "FEMALE", "female", "MALE", "F", "male", "FEMALE", "M"),
age = c(30L, 32L, 54L, 42L, 11L, 34L, 67L, 49L, 27L, 18L, 30L)),
class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"))
uj5u.com熱心網友回復:
sex <- c("fema", "f", "F", "M", "male", "MALe")
我們不需要plyr或任何外部包:
toUpper(substr(sex,1,1))
回傳:
[1] "F" "F" "F" "M" "M" "M"
編輯
像這樣使用上面的解決方案(在 R 中,與其他編程語言相反,我們很少就地改變物件,所以我們幾乎總是想分配我們的值):
df$Sex <- toUpper(substr(df$Sex,1,1))
或者,如果您想保留原始列:
df$Sex_fixed <- toUpper(substr(df$Sex,1,1))
另一個編輯:
根據要求使用plyr::mapvalues以下解決方案:
mre_data$sex_fixed <- plyr::mapvalues(mre_data$sex, c("Male", "MALE", "M", "male", "F", "FEMALE", "female"), c("M", "M", "M", "M", "F", "F", "F"))
mre_data
就是現在:
name sex age sex_fixed
1 John Male 30 M
2 Clara F 32 F
3 Smith MALE 54 M
4 Ray M 42 M
5 karen FEMALE 11 F
6 Ruba female 34 F
7 Josh MALE 67 M
8 Jennifer F 49 F
9 David male 27 M
10 Maria FEMALE 18 F
11 Sam M 30 M
雖然這有效,但對我來說沒有意義,因為我們必須單獨指定每個替換對。但我們真正想要的是對每個條目應用一個規則(單詞的第一個字母,大寫)......(mapvalues適用于我們沒有簡單規則并且必須指定每個替換對的用例)。
OR, and this doesn't make sense at all and you really should use the direct route via x <- toUpper(substr(...)), but here we go - We can combine the "automatic" rules solution with the mapvalues solution to create a very confused and over complicated solution ;) (but at least we don't have to hardcode each replacement pair):
mre_data$sex_fixed2 <- plyr::mapvalues(mre_data$sex, unique(mre_data$sex), toUpper(substr(unique(mre_data$sex),1,1)))
mre_data
Is now:
name sex age sex_fixed sex_fixed2
1 John Male 30 M M
2 Clara F 32 F F
3 Smith MALE 54 M M
4 Ray M 42 M M
5 karen FEMALE 11 F F
6 Ruba female 34 F F
7 Josh MALE 67 M M
8 Jennifer F 49 F F
9 David male 27 M M
10 Maria FEMALE 18 F F
11 Sam M 30 M M
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/318478.html
