簡體   English   中英

更改數據框 - 迭代行中的值

[英]Changing data frame - Iterating through values in rows

我有數據框,只想將字符串中的值更改為整數。

我怎樣才能在R中實現這一目標?

假設這是我的數據:

data.frame(
    X = sample(1:10),
    Y = sample(c("yes", "no"), 10, replace = TRUE),
    Z = sample(c("yes", "no"), 10, replace = TRUE),
    ZZ = sample(c("yes", "no"), 10, replace = TRUE))

我想改變:

使用給定函數f [ex。]更改列Y. 函數f將“是”更改為2,將“否”更改為第二列中的1]

這種功能的例子

f <- function (x) {
 if(x == "yes") {
   return 2;
 }
 else {
   return 11;
 }
}

用給定的函數g改變列ZZ [ex。 功能g將“是”更改為3,將“否”更改為第4列中的4]

這里使用函數ifelse()解決方案。

df<-data.frame(
  X = sample(1:10),
  Y = sample(c("yes", "no"), 10, replace = TRUE),
  Z = sample(c("yes", "no"), 10, replace = TRUE),
  ZZ = sample(c("yes", "no"), 10, replace = TRUE))

df$Y=as.integer(ifelse(df$Y=="yes",2,1))
df$ZZ=as.integer(ifelse(df$ZZ=="yes",3,4))
str(df)
'data.frame':   10 obs. of  4 variables:
 $ X : int  9 4 8 5 1 7 2 10 6 3
 $ Y : int  2 2 1 1 2 1 2 1 1 1
 $ Z : Factor w/ 2 levels "no","yes": 2 1 2 2 1 2 2 1 1 1
 $ ZZ: int  3 3 4 3 3 3 3 4 4 3

編輯

為同一任務創建函數fg

f<-function(x){
  as.integer(ifelse(x=="yes",2,1))
}

g<-function(x){
  as.integer(ifelse(x=="yes",3,4))
}

df$Y=f(df$Y)
df$ZZ=g(df$ZZ)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM