R函数用于修剪数据框。

huangapple go评论53阅读模式
英文:

R functions to trim data frame

问题

以下是一个示例数据框,我想要通过提取不同的列来修剪数据框:

c1<-c(1:10)
c2<-c(1,2,3,4,5,4,3,2,1,9)
c3<-c(11:20)
df<-data.frame(c1,c2,c3)
df

如果我想跳过顶部和底部的整行,可以使用以下方式:

# Skip the first and last row
df_trimmed <- df[-c(1, nrow(df)), ]
df_trimmed

这将得到修剪后的数据框。

英文:

below is a sample data frame and I would like to trim and data frame by extracting different columns:

&gt; c1&lt;-c(1:10)
&gt; c2&lt;-c(1,2,3,4,5,4,3,2,1,9)
&gt; c3&lt;-c(11:20)
&gt; df&lt;-data.frame(c1,c2,c3)
&gt; df
   c1 c2 c3
1   1  1 11
2   2  2 12
3   3  3 13
4   4  4 14
5   5  5 15
6   6  4 16
7   7  3 17
8   8  2 18
9   9  1 19
10 10  9 20

Say if I wanna skip the entire top and bottom row, which shall be like:

R函数用于修剪数据框。

Is there a function where I can extract the data frame or to eliminate certain rows? Thanks so much.

答案1

得分: 1

The dplyr package有多个函数可帮助完成此操作

slice保留行或请求的行(或删除前面带有“-”的行)

df |>
  slice(-c(1, n()))

或者等效地,

slice(df, -c(1, n()))

filter允许您保留具有指定内容的行

df |>
  filter(c1 > 1)

逗号的作用类似于“和”(因此必须同时满足两个要求)

df |>
  filter(
    c1 > 1,
    c3 < 20
  )
英文:

The dplyr package has multiple functions to assist with this

slice keeps the rows or requested (or removes those with a "-" in front of them)

df |&gt;
  slice(-c(1, n()))

or equivalently,

slice(df, -c(1, n()))

filter let's you keep the rows with specified conents

df |&gt;
  filter(c1 &gt; 1)

Commas act like "and" (so both requirements must be true)

df |&gt;
  filter(
    c1 &gt; 1,
    c3 &lt; 20
  )

答案2

得分: 1

你可以像下面这样索引行

> df[2:(nrow(df) - 1), ]
c1 c2 c3
2 2 2 12
3 3 3 13
4 4 4 14
5 5 5 15
6 6 4 16
7 7 3 17
8 8 2 18
9 9 1 19

或者使用 `head` + `tail`

> tail(head(df, -1), -1)
c1 c2 c3
2 2 2 12
3 3 3 13
4 4 4 14
5 5 5 15
6 6 4 16
7 7 3 17
8 8 2 18
9 9 1 19


<details>
<summary>英文:</summary>

You can index rows like below

> df[2:(nrow(df) - 1), ]
c1 c2 c3
2 2 2 12
3 3 3 13
4 4 4 14
5 5 5 15
6 6 4 16
7 7 3 17
8 8 2 18
9 9 1 19

or with `head` + `tail`

> tail(head(df, -1), -1)
c1 c2 c3
2 2 2 12
3 3 3 13
4 4 4 14
5 5 5 15
6 6 4 16
7 7 3 17
8 8 2 18
9 9 1 19


</details>



huangapple
  • 本文由 发表于 2023年6月22日 04:30:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76526925.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定