Home > database >  can define a new column because it is factor
can define a new column because it is factor

Time:08-02

I have a dataset like this:

risk earthquake platarea magnitude area
0.4 no 5 30
0.5 no 6 20
5.5 yes 6 20

I would like to create a new column

i gave that code

df$newrisk <- 0.5*df$magnitude   0.6*df$aarea   3*df$platarea

I got an error message for df$platarea? BUt the platarea will only increase when it is "yes". How can I code that???? the code is right if I omit df$platarea, but i would also include df$platarea but don't know how??

CodePudding user response:

We can create a logical vector

i1 <- df$platarea == "yes"
df$newrisk[i1] <- with(df, 0.5 * magnitude[i1]   0.6 * area[i]   3)

If it is only to change the 3 *, multiply by the logical vector so that FALSE (or 0 will return 0 and TRUE for 'yes' will return 3 as -3 *1 = 3)

df$newrisk <- with(df, 0.5 * magnitude   0.6 * area   3 *i1)

CodePudding user response:

There are three common ways to add a new column to a data frame in R:

  1. Use the $ Operator

df$new <- c(3, 3, 6, 7, 8, 12)

  1. Use Brackets

df['new'] <- c(3, 3, 6, 7, 8, 12)

  1. Use Cbind

df_new <- cbind(df, new)

I leave some examples for further explanation:

#create data frame
df <- data.frame(a = c('A', 'B', 'C', 'D', 'E'),
                 b = c(45, 56, 54, 57, 59))

#view data frame
df

  a  b
1 A 45
2 B 56
3 C 54
4 D 57
5 E 59

Example 1: Use the $ Operator
 

    #define new column to add
new <- c(3, 3, 6, 7, 8)

#add column called 'new'
df$new <- new

#view new data frame
df 

  a  b new
1 A 45   3
2 B 56   3
3 C 54   6
4 D 57   7
5 E 59   8

Example 2: Use Brackets

#define new column to add
new <- c(3, 3, 6, 7, 8)

#add column called 'new'
df['new'] <- new

#view new data frame
df 

  a  b new
1 A 45   3
2 B 56   3
3 C 54   6
4 D 57   7
5 E 59   8

Example 3: Use Cbind

#define new column to add
new <- c(3, 3, 6, 7, 8)

#add column called 'new'
df_new <- cbind(df, new)

#view new data frame
df_new

  a  b new
1 A 45   3
2 B 56   3
3 C 54   6
4 D 57   7
5 E 59   8
  •  Tags:  
  • r
  • Related