使用gsub在data.table中添加新列 [英] Using gsub adding new column in a data.table

查看:86
本文介绍了使用gsub在data.table中添加新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,一个非常基本的问题,解决方案必须非常简单,但我找不到它。

Sorry for a very basic question, solution must be very simple but I'm not able to find it.

尝试使用gsub在data.table,我得到警告
参数'replacement'的长度> 1,并且仅将使用第一个元素,并且所有data.table行都在新列中具有,即第一行的值。

Trying to use gsub adding a new column in a data.table, I got the warning "argument 'replacement' has length > 1 and only the first element will be used", and all data.table rows have, in the new column, the value of the first row.

这里是一个简化的情况:

Here is a semplified case:

dt <- data.table(v1=c(1,2,3) , v2=c("axb","cxxd","exfxgx"))  
dt[ , v3:=gsub("x",v1,v2)]  

新列v3包含带有 1的字符串

The new column v3 contains a string with "1" instead of "x" in all the rows.

使用其他功能,例如

dt[ , v3:=paste(v1,v2)]  

按预期工作。

我正在使用Rstudio v.0.98.1103和R v.3.1 .2,data.table v.1.9.4

I'm using Rstudio v.0.98.1103 , R v.3.1.2, data.table v.1.9.4

推荐答案

dt[, v3 := gsub("x", v1, v2), by = v1]  

这篇关于使用gsub在data.table中添加新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆