Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用R中另一列中元素的第一个元素创建新的dataframe列_R_Dataframe - Fatal编程技术网

使用R中另一列中元素的第一个元素创建新的dataframe列

使用R中另一列中元素的第一个元素创建新的dataframe列,r,dataframe,R,Dataframe,我想在我的数据框中创建一个新列,这样它就由同一数据框中另一列中元素的第一个元素(或两个元素)组成。例如 columnA 1 "1234" 2 "9876" 3 "4567" 变成: columnA columnB 1 "1234" "12" 2 "9876" "98" 3 "4567" "45" 我尝试使用dplyr库,如下所示: dataframe %>% mutate( columnB = col

我想在我的数据框中创建一个新列,这样它就由同一数据框中另一列中元素的第一个元素(或两个元素)组成。例如

   columnA
1   "1234"
2   "9876"
3   "4567"
变成:

   columnA    columnB
1   "1234"       "12"
2   "9876"       "98"
3   "4567"       "45"
我尝试使用dplyr库,如下所示:

dataframe %>%
    mutate( columnB = columnA[1:2] )
但这是试图检索前两行


如果有人知道如何快速完成这个任务(最好是使用dplyr库),我将非常感激。提前感谢。

感谢您的快速回复。它工作得很好。
df <- data.frame(columnA=c("1234","9876","4567"))
df$columnB <- substr(df$columnA,1,2)           
 #   columnA columnB
 # 1    1234      12
 # 2    9876      98
 # 3    4567      45 
df <- df %>% mutate(columnB = substr(columnA,1,2))