相关疑难解决方法(0)

dplyr mutate rowSums计算或自定义函数

我试图从行计算中改变一个新变量,rowSums如下所示

iris %>% 
  mutate_(sumVar = 
            iris %>% 
            select(Sepal.Length:Petal.Width) %>%
            rowSums)
Run Code Online (Sandbox Code Playgroud)

结果是"sumVar"被截断为其第一个值(10.2):

Source: local data frame [150 x 6]
Groups: <by row>

   Sepal.Length Sepal.Width Petal.Length Petal.Width Species sumVar
1           5.1         3.5          1.4         0.2  setosa   10.2
2           4.9         3.0          1.4         0.2  setosa   10.2
3           4.7         3.2          1.3         0.2  setosa   10.2
4           4.6         3.1          1.5         0.2  setosa   10.2
5           5.0         3.6          1.4         0.2  setosa   10.2
6           5.4         3.9          1.7         0.4  setosa   10.2
..
Warning message:
Truncating vector to length 1 
Run Code Online (Sandbox Code Playgroud)

它应该 …

r dplyr

54
推荐指数
4
解决办法
4万
查看次数

R:data.table count!每行NA

我试图计算每行不包含NA的列数,并将该值放入该行的新列中.

示例数据:

library(data.table)

a = c(1,2,3,4,NA)
b = c(6,NA,8,9,10)
c = c(11,12,NA,14,15)
d = data.table(a,b,c)

> d 
    a  b  c
1:  1  6 11
2:  2 NA 12
3:  3  8 NA
4:  4  9 14
5: NA 10 15
Run Code Online (Sandbox Code Playgroud)

我想要的输出将包括一个新列num_obs,其中包含每行非NA条目的数量:

    a  b  c num_obs
1:  1  6 11       3
2:  2 NA 12       2
3:  3  8 NA       2
4:  4  9 14       3
5: NA 10 15       2
Run Code Online (Sandbox Code Playgroud)

我现在已经阅读了好几个小时,到目前为止,我所提出的最好的是循环遍历行,我知道这在R或data.table中是不可取的.我相信有更好的方法可以做到这一点,请赐教.

我糟糕的方式:

len = (1:NROW(d))
for (n in …
Run Code Online (Sandbox Code Playgroud)

r data.table

12
推荐指数
2
解决办法
4236
查看次数

替换R data.table中的Inf /以colum显示Inf的数量

我无法弄清楚如何使用is.na(x)函数来表示R中的无限数字与数据表或每列显示有多少Inf:colSums(is.infinite(x))

我使用以下示例数据集:

DT <- data.table(a=c(1/0,1,2/0),b=c("a","b","c"),c=c(1/0,5,NA))
DT
     a b   c
1: Inf a Inf
2:   1 b   5
3: Inf c   NA
colSums(is.na(DT))
a b c 
0 0 1 
colSums(is.infinite(DT))
Error in is.infinite(DT) : default method not implemented for type 'list'
DT[is.na(DT)] <- 100
 DT
     a b   c
1: Inf a Inf
2:   1 b   5
3: Inf c 100

DT[is.infinite(DT)] <- 100
Error in is.infinite(DT) : default method not implemented for type 'list'
Run Code Online (Sandbox Code Playgroud)

我在这篇文章中发现如何用NA取代Inf,但我想说应该有更好的方法来实现这一点,例如is.infinite.我想看看每列的Inf,有关于此的任何想法吗?

非常感谢.BR蒂姆

r infinite na data.table

2
推荐指数
1
解决办法
2234
查看次数

标签 统计

r ×3

data.table ×2

dplyr ×1

infinite ×1

na ×1