Adding New Column To A Data Frame in R

That is a quite noob tip and me, as a noob in R, was pleased to do that. Let’s say you have a data.frame named “saida” with four columns “A”, “B”, “C”, “D”.

>saida # let's see the content of our data.frame "saida"

    A   B    C    D

1   1   64   20   0
2   2   64   20   3
3   3   64   20   3
4   4   64   20   1
5   5   64   20   4
>saida["MY_NEW_COLUMN"] <- NA # That creates the new column named "MY_NEW_COLUMN" filled with "NA"
>saida$MY_NEW_COLUMN <- saida$C - saida$D  # As an example, the new column receives the result of C - D
>saida # let's see the result

    A   B    C    D   MY_NEW_COLUMN

1   1   64   20   0   20
2   2   64   20   3   17
3   3   64   20   3   17
4   4   64   20   1   19
5   5   64   20   4   16

If you want to add many columns, one way to accomplish that is using a list with the names of the new columns, e.g.,:

saida[c("E","F","G","H","I")] <- NA # adds those many columns labeled from E to I.

I am sure there is a more elegant way to accomplish the same result but this is the only way that I know.

Advertisements