R函数用于修剪数据框。

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

R functions to trim data frame

问题

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

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

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

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

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

英文:

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

  1. &gt; c1&lt;-c(1:10)
  2. &gt; c2&lt;-c(1,2,3,4,5,4,3,2,1,9)
  3. &gt; c3&lt;-c(11:20)
  4. &gt; df&lt;-data.frame(c1,c2,c3)
  5. &gt; df
  6. c1 c2 c3
  7. 1 1 1 11
  8. 2 2 2 12
  9. 3 3 3 13
  10. 4 4 4 14
  11. 5 5 5 15
  12. 6 6 4 16
  13. 7 7 3 17
  14. 8 8 2 18
  15. 9 9 1 19
  16. 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保留行或请求的行(或删除前面带有“-”的行)

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

或者等效地,

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

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

  1. df |>
  2. filter(c1 > 1)

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

  1. df |>
  2. filter(
  3. c1 > 1,
  4. c3 < 20
  5. )
英文:

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)

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

or equivalently,

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

filter let's you keep the rows with specified conents

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

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

  1. df |&gt;
  2. filter(
  3. c1 &gt; 1,
  4. c3 &lt; 20
  5. )

答案2

得分: 1

  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

  1. 或者使用 `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

  1. <details>
  2. <summary>英文:</summary>
  3. 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

  1. 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

  1. </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:

确定