0

I have a dataframe df that contains a factor in column A (e.g. companies | persons). I have data in column B and C. Now I want to create a new variable/column that uses data from B if it is a company and uses data from C it is a private person.

df$D <- (when (A == company) then B else when (B == person) then C

Thank you for all responses.

3
  • df$D <- ifelse(df$A == 'company', df$B, df$C) Commented Mar 14, 2022 at 12:05
  • Very good. Thanky you! What would I need to do if A was not binary but included just different names (Alice, Bob, Charles, ...)? Commented Mar 14, 2022 at 12:19
  • Look at case_when from the dplyr package, which is like the non-binary version of ifelse Commented Mar 14, 2022 at 12:21

1 Answer 1

1

Sample code:

ifelse example as suggested by @Allan Cameron

df$d <- ifelse(df$a == "company", df$b, df$c)

  df

         a  b  c  d
1  company  1 10  1
2  company  2 20  2
3  company  3 30  3
4  company  4 40  4
5  company  5 50  5
6  company  6 60  6
7  persons  7 70 70
8  persons  8 80 80
9  persons  9 10 10
10 persons 10 10 10
11 persons 11 10 10

case_when example from dplyr()

df %>% 
   mutate(e = case_when (b <=6 & c>=10 ~ "company", d > 6 ~ "persons", b==9 & c==10 & d==10~"NA"))

df

         a  b  c  d       e
1  company  1 10  1 company
2  company  2 20  2 company
3  company  3 30  3 company
4  company  4 40  4 company
5  company  5 50  5 company
6  company  6 60  6 company
7  persons  7 70 70 persons
8  persons  8 80 80 persons
9  persons  9 10 10      NA
10 persons 10 10 10 company
11 persons 11 10 10 company

Sample data:

a<-c("company","company","company","company","company","company","persons","persons","persons","persons","persons")
b<-c(1,2,3,4,5,6,7,8,9,10,11)
c<-c(10,20,30,40,50,60,70,80,10,10,10)


df<-cbind(a,b,c)
df<-data.frame(df)

df$a<-factor(df$a, levels=c("company","persons"))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.