3

重複の可能性:
同じ df 内の別の列に基づいて df$column に値を割り当てる

データフレームがあるとします:

table<- data.frame(population=c(100, 300, 5000, 2000, 900, 2500), habitat=c(1,2,3,4,5,6))

ここで、人口 < 500 の場合は 1、500<=人口 <1000 の場合は 2、1000<=人口 <2000 の場合は 3、2000<=人口<3000 の場合は 4、3000 の場合は 5 の新しい列 table$size を追加します。 <=人口<=5000

別の列の値を条件とするバイナリTRUE / FALSE結果を持つ列を作成する方法しか知りません。

table$size <- (table$population<1000) 

しかし、条件ごとに異なる数値を取得するためにそれを行うかどうかはわかりません。誰でもこれについて助けてもらえますか?

4

3 に答える 3

9

は基本関数であるdata.frame tableため、まず a を呼び出さないでください。table

使用できますfindInterval

df <- data.frame(population=c(100, 300, 5000, 2000, 900, 2500), 
                 habitat=c(1,2,3,4,5,6))
v <- c(-Inf,500,1000,2000,3000,5000)
df$size <- findInterval(df$population,v,all.inside = TRUE)
  population habitat size
1        100       1    1
2        300       2    1
3       5000       3    5
4       2000       4    4
5        900       5    2
6       2500       6    4

all.inside = TRUE5000 をサイズ 5 として定義したかったので使用しましたが、値はそれを超えることはできないと想定しています。可能であれば、次のようなものを使用できます

v <- c(-Inf,500,1000,2000,3000,5001,Inf).

于 2012-11-24T10:33:31.817 に答える
4

マッピングの関数を定義できます。したがって、さまざまなビンを含めます。

mysize <- function(x){
  if(x<500)
   return(1)
  if(500 <= x & x < 1000)
    return(2)
  if(1000<=x & x<2000)
    return(3)
  if(2000<=x & x<3000)
    return(4)
  if(3000<=x & x <=5000)
    return(5)
  else
    return(NA)
}

次に、この関数を人口列に適用して、必要な新しい列を追加できます。

table$population.bin <- sapply(table$population, mysize)
table
于 2012-11-24T10:13:54.630 に答える
2

5 が <=5000 ではなく <5001 の任意の数であることを処理できる限り、おそらくラベル付きのカット機能が必要です。

# look at the help window
?cut

# initiate your table
table <- 
    data.frame(
        population = c( 100 , 300, 5000, 2000, 900, 2500) , 
        habitat = 1:6
    )

# create a new column with the desired cutpoints
table$size <- 
    cut( 
        # input data
        table$population , 
        # cut points
        c( -Inf , 500 , 1000 , 2000 , 3000 , 5001 ) , 
        # label values (character strings work too)
        labels = 1:5 ,
        # interval closed on the right?
        right = FALSE
    )
于 2012-11-24T10:32:08.830 に答える