编辑数据框列表内数据框中变量的单元格条目
定义:
> dats <- list( df1 = data.frame(a=sample(1:3), b = as.factor(rep("325.049072M",3))),
+ df2 = data.frame(a=sample(1:3), b = as.factor(rep("325.049072M",3))))
> dats
$df1
a b
1 3 325.049072M
2 2 325.049072M
3 1 325.049072M
$df2
a b
1 2 325.049072M
2 1 325.049072M
3 3 325.049072M
我想从每个数据框中的 b 列中删除 M 字符。
在一个简单的框架中:
> t<-c("325.049072M","325.049072M")
> t
[1] "325.049072M" "325.049072M"
> t <- substr(t, 1, nchar(t)-1)
> t
[1] "325.049072" "325.049072"
但是在嵌套的框架中,如何进行?这是一次令人遗憾的尝试:
> dats <- list( df1 = data.frame(a=sample(1:3), b = as.factor(rep("325.049072M",3))),
+ df2 = data.frame(a=sample(1:3), b = as.factor(rep("325.049072M",3))))
> dats
$df1
a b
1 3 325.049072M
2 1 325.049072M
3 2 325.049072M
$df2
a b
1 2 325.049072M
2 3 325.049072M
3 1 325.049072M
> for(i in seq(along=dats)) {
+ dats[[i]]["b"] <-
+ substr(dats[[i]]["b"], 1, nchar(dats[[i]]["b"])-1)
+ }
> dats
$df1
a b
1 3 c(1, 1, 1
2 1 c(1, 1, 1
3 2 c(1, 1, 1
$df2
a b
1 2 c(1, 1, 1
2 3 c(1, 1, 1
3 1 c(1, 1, 1
Define:
> dats <- list( df1 = data.frame(a=sample(1:3), b = as.factor(rep("325.049072M",3))),
+ df2 = data.frame(a=sample(1:3), b = as.factor(rep("325.049072M",3))))
> dats
$df1
a b
1 3 325.049072M
2 2 325.049072M
3 1 325.049072M
$df2
a b
1 2 325.049072M
2 1 325.049072M
3 3 325.049072M
I want to remove the M character from column b in each data frame.
In a simple framework:
> t<-c("325.049072M","325.049072M")
> t
[1] "325.049072M" "325.049072M"
> t <- substr(t, 1, nchar(t)-1)
> t
[1] "325.049072" "325.049072"
But in a nested one, how to proceed? Here is one sorry attempt:
> dats <- list( df1 = data.frame(a=sample(1:3), b = as.factor(rep("325.049072M",3))),
+ df2 = data.frame(a=sample(1:3), b = as.factor(rep("325.049072M",3))))
> dats
$df1
a b
1 3 325.049072M
2 1 325.049072M
3 2 325.049072M
$df2
a b
1 2 325.049072M
2 3 325.049072M
3 1 325.049072M
> for(i in seq(along=dats)) {
+ dats[[i]]["b"] <-
+ substr(dats[[i]]["b"], 1, nchar(dats[[i]]["b"])-1)
+ }
> dats
$df1
a b
1 3 c(1, 1, 1
2 1 c(1, 1, 1
3 2 c(1, 1, 1
$df2
a b
1 2 c(1, 1, 1
2 3 c(1, 1, 1
3 1 c(1, 1, 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 lapply(和一些强制)来做到这一点:
如果您需要该变量作为因子,您可以在
stripM
中包含一行,将 is 转换回因子,类似x$b <- as.factor(x$b)
。You can do this with
lapply
(and some coercion):If you need that variable as a factor, you can include a line in
stripM
that converts is back to a factor, something likex$b <- as.factor(x$b)
.尝试使用
gsub
而不是substr
- 像这样:当然,您需要弄清楚如何递归到列表元素等,但我想您得到了图片...
Try using
gsub
instead ofsubstr
- something like this:of course, you need to figure out how are you going to recurse into list elements etc. but I guess you get the picture...
好吧,这是另一种可能性,虽然不简洁,但很容易理解:
我不得不说,我发现整个
[[
与[
引用非常神秘。我通过反复试验来进行。有什么好的解释吗?
Ok, here is another possibility, not neat, but intelligible:
I have to say that I find the whole
[[
versus[
referencing very cryptic.I proceed by trial and error. Any pointers to a good explanation?