記住這個函數!記住這個函數!記住這個函數!
重要的事情說三遍,為了讓你能更清醒地記住,我再說一遍,記住這個函數!
dput
是導出數據結構供重復使用的函數,這是跟別人交流或者請教問題的一個重要函數。比如你在用R分析的時候遇到問題了,有問題的是對某個列表或者數據框進行操作,該怎么讓別人可以重復你的錯誤然后幫你找錯呢?這就是這個函數存在的意義。
舉個例子,假如你有這樣一個數據框:
> staff
name salary years_old
1 zhangsan 1200 20
2 lisi 2200 30
3 wangwu 3200 40
然后你想給每個人漲200塊并更新表格,想做個簡單計算:
> staff$salary <- staff$salary + 200
Error in staff$salary + 200 : non-numeric argument to binary operator
我擦,什么鬼,英文我不懂,想請教下別人怎么幫你解決,你這時候就用的上dput
函數了。
于是你使用這個函數把數據存取,發布到給專家:
> dput(staff)
structure(list(name = structure(c(3L, 1L, 2L), .Label = c("lisi",
"wangwu", "zhangsan"), class = "factor"), salary = c("1200",
"2200", "3200"), years_old = c(20, 30, 40)), .Names = c("name",
"salary", "years_old"), row.names = c(NA, -3L), class = "data.frame")
為了區別,專家用a表示staff
把你的數據結構在他的電腦上重現:
> a <- structure(list(name = structure(c(3L, 1L, 2L), .Label = c("lisi", "wangwu", "zhangsan"), class = "factor"), salary = c("1200",
+ "2200", "3200"), years_old = c(20, 30, 40)), .Names = c("name", "salary", "years_old"), row.names = c(NA, -3L), class = "data.frame")
然后就可以幫你檢查了:
> str(a)
'data.frame': 3 obs. of 3 variables:
$ name : Factor w/ 3 levels "lisi","wangwu",..: 3 1 2
$ salary : chr "1200" "2200" "3200"
$ years_old: num 20 30 40
喔~原來salary
變量是字符向量,不能做數學運算。幫你修改:
> a$salary <- as.integer(a$salary)
> a$salary <- a$salary + 200
> a
name salary years_old
1 zhangsan 1400 20
2 lisi 2400 30
3 wangwu 3400 40
導出:
> dput(a)
structure(list(name = structure(c(3L, 1L, 2L), .Label = c("lisi",
"wangwu", "zhangsan"), class = "factor"), salary = c(1400, 2400,
3400), years_old = c(20, 30, 40)), .Names = c("name", "salary",
"years_old"), row.names = c(NA, -3L), class = "data.frame")
然后你把結果拷貝并導回,工作完成:
> salary <- structure(list(name = structure(c(3L, 1L, 2L), .Label = c("lisi",
+ "wangwu", "zhangsan"), class = "factor"), salary = c(1400, 2400,
+ 3400), years_old = c(20, 30, 40)), .Names = c("name", "salary",
+ "years_old"), row.names = c(NA, -3L), class = "data.frame")
> salary
name salary years_old
1 zhangsan 1400 20
2 lisi 2400 30
3 wangwu 3400 40