Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R transform() Function - Data Transformation

R transform() Function - Data Transformation

R Language Examples R Language Examples

The R transform() function is used to add new columns or modify existing columns in a data frame.

transform() makes data transformation more concise, without repeatedly writing the df$ prefix.

The syntax of the transform() function is as follows:

transform(`_data`, ...)

Parameter Description:

Example

Original data frame

df

<-

data.frame

(

  Name

=

c

(

"Zhang San"

,

"Li Si"

,

"Wang Wu"

,

"Zhao Liu"

)

,

  Math

=

c

(

88

,

92

,

76

,

85

)

,

  English

=

c

(

90

,

88

,

82

,

78

)

,

  stringsAsFactors

=

FALSE

)

print

(

"Original data:"

)

print

(

df

)

Add new columns: total score and average score

df_new

<-

transform

(

df

,

  Total score

=

Math

English,

  Average score

=

round

(

(

Math

English

)

/

2

,

1

)

,

  Evaluation

=

ifelse

(

Average score

=

85

,

"Excellent"

,

ifelse

(

Average score

=

80

,

"Good"

,

"Fair"

)

)

)

print

(

"After adding new columns:"

)

print

(

df_new

)

The output of the code above is:

[1] "原始数据:"

  姓名 数学 英语

1 张三   88   90

2 李四   92   88

3 王五   76   82

4 赵六   85   78

[1] "添加新列后:"

  姓名 数学 英语 总分 平均分 评价

1 张三   88   90  178   89.0 优秀

2 李四   92   88  180   90.0 优秀

3 王五   76   82  158   79.0 一般

4 赵六   85   78  163   81.5 良好

R Language Examples R Language Examples