There are 3 usual techniques so as to add a untouched column to a knowledge body in R:
1. Importance the $ Operator
df$untouched <- c(3, 3, 6, 7, 8, 12)
2. Importance Brackets
df['new'] <- c(3, 3, 6, 7, 8, 12)
3. Importance Cbind
df_new <- cbind(df, untouched)
This instructional supplies examples of how one can usefulness every of those modes in observe the use of please see information body:
#manufacture information body
df <- information.body(a = c('A', 'B', 'C', 'D', 'E'),
b = c(45, 56, 54, 57, 59))
#view information body
df
a b
1 A forty five
2 B 56
3 C 54
4 D 57
5 E 59
Instance 1: Importance the $ Operator
Please see code displays how one can upload a column to a knowledge body through the use of the $ operator:
#outline untouched column so as to add
untouched <- c(3, 3, 6, 7, 8)
#upload column referred to as 'untouched'
df$untouched <- untouched
#view untouched information body
df
a b untouched
1 A forty five 3
2 B 56 3
3 C 54 6
4 D 57 7
5 E 59 8
Instance 2: Importance Brackets
Please see code displays how one can upload a column to a knowledge body through the use of brackets:
#outline untouched column so as to add
untouched <- c(3, 3, 6, 7, 8)
#upload column referred to as 'untouched'
df['new'] <- untouched
#view untouched information body
df
a b untouched
1 A forty five 3
2 B 56 3
3 C 54 6
4 D 57 7
5 E 59 8
Instance 3: Importance Cbind
Please see code displays how one can upload a column to a knowledge body through the use of the cbind serve as, which is cut for column-bind:
#outline untouched column so as to add
untouched <- c(3, 3, 6, 7, 8)
#upload column referred to as 'untouched'
df_new <- cbind(df, untouched)
#view untouched information body
df_new
a b untouched
1 A forty five 3
2 B 56 3
3 C 54 6
4 D 57 7
5 E 59 8
You’ll be able to if truth be told usefulness the cbind serve as so as to add a couple of untouched columns without delay:
#outline untouched columns so as to add
new1 <- c(3, 3, 6, 7, 8)
new2 <- c(13, 14, 16, 17, 20)
#upload columns referred to as 'new1' and 'new2'
df_new <- cbind(df, new1, new2)
#view untouched information body
df_new
a b new1 new2
1 A forty five 3 13
2 B 56 3 14
3 C 54 6 16
4 D 57 7 17
5 E 59 8 20
Bonus: Eager Column Names
Upcoming including a number of columns to a knowledge body, you’ll usefulness theĀ colnames() serve as to specify the column names of the untouched information body:
#manufacture information body
df <- information.body(a = c('A', 'B', 'C', 'D', 'E'),
b = c(45, 56, 54, 57, 59),
new1 = c(3, 3, 6, 7, 8),
new2 = c(13, 14, 16, 17, 20))
#view information body
df
a b new1 new2
1 A forty five 3 13
2 B 56 3 14
3 C 54 6 16
4 D 57 7 17
5 E 59 8 20
#specify column names
colnames(df) <- c('a', 'b', 'c', 'd')
#view information body
df
a b c d
1 A forty five 3 13
2 B 56 3 14
3 C 54 6 16
4 D 57 7 17
5 E 59 8 20
You’ll be able to in finding extra R tutorials right here.