R transform() Function - Data Transformation
The R transform() function is used to add new columns or modify existing columns in a data frame.
transform() makes data transformation operations more concise, avoiding the need to repeatedly write the df$ prefix.
The syntax format of the transform() function is as follows:
transform(`_data`, ...)
Parameter description:
_dataInput data frame.
...Definition of new columns (e.g., new column name = expression).
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", "Average"))
)
print("After adding new columns:")
print(df_new)
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", "Average"))
)
print("After adding new columns:")
print(df_new)
Executing the above code outputs the following result:
[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 良好Other extensions
R Language Examples