簡體   English   中英

在沒有for循環的情況下處理R中的數據幀

[英]Manipulating dataframe in R without for loop

我在R中有一個數據框,其中有3列和數百萬行:

> df
   col1 col2 col3
1   one  1.1    4
2   two  1.5    1
3 three  1.7    5
.    ..   ..   ..

我想根據其中兩列進行計算。 我想創建一個基本上像這樣的列:

if col1 == "one", then result = col2*.0.5, 
else if col1 == "two, then result = col2*0.6
else if ...

但是缺少對所有數百萬行執行非常大的for循環的方法,我想不出沒有for循環的一種更“ R”的方式可以做到這一點。 有什么建議么?

謝謝!

解決方案的小例子。 不知道這是否是最有效的方法,但是可以解決問題。

df = data.frame(col1=c(1,1,2,2,3),col2=c(2,2,2,2,2))

df$col3=NA
df$col3 = ifelse(df$col1==1, df$col2*1.5, df$col3)
df$col3 = ifelse(df$col1==2, df$col2*2.5, df$col3)
df$col3 = ifelse(df$col1==3, df$col2*3.5, df$col3)
  1. 如果col1 == 1,則col3 = col2 * 1.5
  2. 如果col1 == 2,則col3 = col2 * 2.5
  3. 如果col1 == 3,則col3 = col2 * 3.5

希望這可以幫助。

向量化的方式可能如下。

# make up some data
set.seed(525)
col1 <- sample(c("one", "two", "three"), 20, TRUE)
col2 <- runif(20)
col3 <- rnorm(20)
dat <- data.frame(col1, col2, col3, stringsAsFactors = FALSE)

# where to hold the result
result <- numeric(nrow(dat))

# first condition
inx <- dat$col1 == "one"
result[inx] <- dat[inx, "col2"]*0.5

# second condition
inx <- dat$col1 == "two"
result[inx] <- dat[inx, "col2"]*0.6

result

個人會使用鍵乘數hash_map,因為沒人願意編寫許多if-else語句,請查看此演示:

1.准備數據:

> c1 <- c("one", "two", "three")
> c2 <- sample(10, 3)
> df <- data.frame(c1, c2)
> df$c1 <- as.character(df$c1)
> df
     c1 c2
1   one  4
2   two 10
3 three  5

2.使用setNames定義鍵乘數hash_map:

> key <- c("one", "two", "three")
> multiplier <- c(0.5, 0.6, 0.7)
> my.multiplier <- setNames(as.list(multiplier), key)
> my.multiplier
$one
[1] 0.5

$two
[1] 0.6

$three
[1] 0.7

3.僅一行代碼:

> df$c3 <- df$c2 * as.numeric(my.multiplier[df$c1])
> df
     c1 c2  c3
1   one  4 2.0 #4 * 0.5
2   two 10 6.0 #10 * 0.6
3 three  5 3.5 #5 * 0.7

暫無
暫無

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

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