要在R数据帧列中用下划线替换两个单词之间的空格,可以使用gsub函数。例如,如果我们有一个名为df的数据框,其中包含字符列x,其中两个单词之间有一个空格,则可以使用命令df $x <-gsub(“”,“ _”,df $X)
考虑以下数据帧-
x1<-sample(c("id 1","id 2","id 3","id 4"),20,replace=TRUE) x2<-rpois(20,5) df1<-data.frame(x1,x2) df1输出结果
x1 x2 1 id 4 6 2 id 4 5 3 id 1 6 4 id 3 8 5 id 4 12 6 id 4 8 7 id 3 2 8 id 3 5 9 id 4 8 10 id 1 1 11 id 3 4 12 id 3 5 13 id 2 3 14 id 1 2 15 id 3 5 16 id 1 8 17 id 4 8 18 id 3 5 19 id 2 2 20 id 3 4
用下划线替换id和x1列中数字之间的空格-
df1$x1<-gsub(" ", "_", df1$x1) df1输出结果
x1 x2 1 id_4 6 2 id_4 5 3 id_1 6 4 id_3 8 5 id_4 12 6 id_4 8 7 id_3 2 8 id_3 5 9 id_4 8 10 id_1 1 11 id_3 4 12 id_3 5 13 id_2 3 14 id_1 2 15 id_3 5 16 id_1 8 17 id_4 8 18 id_3 5 19 id_2 2 20 id_3 4
y1<-sample(c("class 1","class 2","class 3"),20,replace=TRUE) y2<-rnorm(20) df2<-data.frame(y1,y2) df2输出结果
y1 y2 1 class 1 0.62986928 2 class 2 1.65731515 3 class 3 -1.13406383 4 class 1 -0.35842133 5 class 1 0.58141698 6 class 3 -0.18424254 7 class 3 -1.05955455 8 class 2 -0.80841041 9 class 3 1.05838028 10 class 2 -1.06141883 11 class 3 -0.54195571 12 class 3 -0.18038280 13 class 2 0.75236011 14 class 2 -0.55374067 15 class 1 0.38737080 16 class 3 0.35892853 17 class 2 -0.44576804 18 class 1 0.62543133 19 class 2 -0.05862987 20 class 1 -0.01508226
用下划线替换id和y1列中数字之间的空格-
df2$y1<-gsub(" ", "_",df2$y1) df2输出结果
y1 y2 1 class_1 0.62986928 2 class_2 1.65731515 3 class_3 -1.13406383 4 class_1 -0.35842133 5 class_1 0.58141698 6 class_3 -0.18424254 7 class_3 -1.05955455 8 class_2 -0.80841041 9 class_3 1.05838028 10 class_2 -1.06141883 11 class_3 -0.54195571 12 class_3 -0.18038280 13 class_2 0.75236011 14 class_2 -0.55374067 15 class_1 0.38737080 16 class_3 0.35892853 17 class_2 -0.44576804 18 class_1 0.62543133 19 class_2 -0.05862987 20 class_1 -0.01508226