我使用的是R编程语言。假设我有以下数据集:
#create data
my_data <- data.frame(
"name" = c("john", "jason", "jack", "jim", "john", "jason", "jack", "jim" ),
"points_1" = c("150", "165", "183", "191", "151", "166", "184", "192"),
"points_2" = c("250", "265", "283", "291", "251", "266", "284", "292")
)
#view data
my_data
name points_1 points_2
1 john 150 250
2 jason 165 265
3 jack 183 283
4 jim 191 291
5 john 151 251
6 jason 166 266
7 jack 184 284
8 jim 192 292
我正在尝试创建一个最终数据集,其外观如下:
my_data_final <- data.frame(
"name" = c("john", "jason", "jack", "jim", "john", "jason", "jack", "jim" ),
"points_1" = c("150", "165", "183", "191", "151", "166", "184", "192"),
"points_2" = c("250", "265", "283", "291", "251", "266", "284", "292"),
"var1" = c("< 150", "< 165", "< 183", " < 191", " < 151", " < 166", " < 184", "< 192"),
"var2" = c("<150 and > 250", "< 165 and > 265", "<183 and > 283", "< 191 and 291", "<150 and > 250", "< 165 and > 265", "<183 and > 283", "< 191 and 291"),
"var3" = c(">250", ">265", ">283", ">291", ">251", ">266", ">284", ">292")
)
#view desired data
my_data_final
name points_1 points_2 var1 var2 var3
1 john 150 250 < 150 <150 and > 250 >250
2 jason 165 265 < 165 < 165 and > 265 >265
3 jack 183 283 < 183 <183 and > 283 >283
4 jim 191 291 < 191 < 191 and 291 >291
5 john 151 251 < 151 <150 and > 250 >251
6 jason 166 266 < 166 < 165 and > 265 >266
7 jack 184 284 < 184 <183 and > 283 >284
8 jim 192 292 < 192 < 191 and 291 >292
我尝试手动创建“迷你变量”,并将它们手动组合成所需的格式:
#example (from here: https://dev59.com/VlfUa4cB1Zd3GeqPIoAy) :
my_data$var_1a = ">"
my_data$var_1 <- as.numeric(paste(my_data$points_1, my_data$var_1a, sep = ""))
但这将导致以下“警告”和NA值:
Warning message:
NAs introduced by coercion
my_data
name points_1 points_2 var1 var2 points_2.1 var_1a var_1
1 john 150 250 < 150 <150 and > 250 >250 > NA
2 jason 165 265 < 165 < 165 and > 265 >265 > NA
3 jack 183 283 < 183 <183 and > 283 >283 > NA
4 jim 191 291 < 191 < 191 and 291 >291 > NA
5 john 151 251 < 151 <150 and > 250 >251 > NA
6 jason 166 266 < 166 < 165 and > 265 >266 > NA
7 jack 184 284 < 184 <183 and > 283 >284 > NA
8 jim 192 292 < 192 < 191 and 291 >292 > NA
有人可以向我展示如何修复此错误并创建所需的变量“var1”,“var2”和“var3”吗?
谢谢
sprintf
更加明确 - 例如:with(my_data, sprintf("<%1$s ,<%1$s and >%2$s, >%2$s", points_1, points_2))
- thelatemail