[英]R Data frame operations
我正在嘗試使用數據框行進行一些操作。 假設我有下一個數據框:
Label<-c(‘A’, ‘A’,’B’,’B’,’A’,’B’,’A’,’X’,’Y’)
Var <- c(1,2,4,7,3,4,6,10,13)
Data<- data.frame(Label,Var)
我希望當Label = A時,Var中的值乘以X,而當label = B時,Y中乘以。
我試圖編寫一個函數,但是沒有成功,可能是我缺乏使用數據框架的經驗。
感謝您的幫助!
快速答案:
library(tidyverse)
Label<-c(‘A’, ‘A’,’B’,’B’,’A’,’B’,’A’,’X’,’Y’)
Var <- c(1,2,4,7,3,4,6,10,13)
Dat <- data_frame(Label,Var) #use data_frame and don't call the dataframe 'Data'
Dat <- Dat %>% # a pipe moves to next command
mutate( #to create a new variable
new_var =
case_when( #runs a series of ifelse statements
Label == 'A' ~ Var*X, #framework: if ~ then
Label == 'B' ~ Var*Y
)
)
一個好的老而簡單的base
解決方案怎么樣?
X <- 3
Y <- 2
Data$NewVar <- with(Data, ifelse(Label == "A", Var * X, Var * Y))
Data
Label Var NewVar
1 A 1 3
2 A 2 6
3 B 4 8
4 B 7 14
5 A 3 9
6 B 4 8
7 A 6 18
8 X 10 20
9 Y 13 26
ifelse
評估第一個條件是否為真,然后評估下一條語句,否則評估第二條。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.