I've been struggling to create a new variable which contains only the first seven characters of an existing variable. Sorry if this if obvious but I've struggled to find an answer which meets my needs on Google/Stack Overflow.
我一直在努力创建一个新变量,它只包含现有变量的前7个字符。如果这是显而易见的,请见谅,但是我一直在努力寻找一个能够满足我对谷歌/Stack Overflow的需求的答案。
My data looks like this:
我的数据是这样的:
variable
UKM5001028
UKM5001028
UKM5001028
UKM5001028
I want to have:
我想要:
variable2
UKM5001
UKM5001
UKM5001
UKM5001
I tried the below code and succeeded in trimming at the 7th character, but it tried to print the whole output, when I want to make a new variable:
我尝试了下面的代码,并成功地对第7个字符进行了修剪,但是当我想要创建一个新的变量时,它尝试打印整个输出:
variable2<-mydata$variable
substr(variable2, 1, 7)
2 个解决方案
#1
4
You are passing wrong argument to substr
将错误的参数传递给substr
Try
试一试
variable2 <- substr(mydata$variable,1,7)
#2
0
You need to store the output of substr(variable2, 1, 7)
into variable2
. Currently you're printing only
您需要将substr(variable2,1,7)的输出存储到variable2中。目前你只打印
variable2<-mydata$variable
variable2<-substr(variable2, 1, 7)
#1
4
You are passing wrong argument to substr
将错误的参数传递给substr
Try
试一试
variable2 <- substr(mydata$variable,1,7)
#2
0
You need to store the output of substr(variable2, 1, 7)
into variable2
. Currently you're printing only
您需要将substr(variable2,1,7)的输出存储到variable2中。目前你只打印
variable2<-mydata$variable
variable2<-substr(variable2, 1, 7)